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