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