github.com/paweljw/pop@v4.13.1+incompatible/slices/map.go (about) 1 package slices 2 3 import ( 4 "database/sql/driver" 5 "encoding/json" 6 7 "errors" 8 ) 9 10 // Map is a map[string]interface. 11 type Map map[string]interface{} 12 13 // Interface implements the nulls.nullable interface. 14 func (m Map) Interface() interface{} { 15 return map[string]interface{}(m) 16 } 17 18 // Scan implements the sql.Scanner interface. 19 // It allows to read the map from the database value. 20 func (m *Map) Scan(src interface{}) error { 21 b, ok := src.([]byte) 22 if !ok { 23 return errors.New("scan source was not []byte") 24 } 25 err := json.Unmarshal(b, m) 26 if err != nil { 27 return err 28 } 29 return nil 30 } 31 32 // Value implements the driver.Valuer interface. 33 // It allows to convert the map to a driver.value. 34 func (m Map) Value() (driver.Value, error) { 35 b, err := json.Marshal(m) 36 if err != nil { 37 return nil, err 38 } 39 return string(b), nil 40 } 41 42 // UnmarshalJSON will unmarshall JSON value into 43 // the map representation of this value. 44 func (m Map) UnmarshalJSON(b []byte) error { 45 var stuff map[string]interface{} 46 err := json.Unmarshal(b, &stuff) 47 if err != nil { 48 return err 49 } 50 for key, value := range stuff { 51 m[key] = value 52 } 53 return nil 54 } 55 56 // UnmarshalText will unmarshall text value into 57 // the map representation of this value. 58 func (m Map) UnmarshalText(text []byte) error { 59 err := json.Unmarshal(text, &m) 60 if err != nil { 61 return err 62 } 63 return nil 64 }