/
json_storer.go
47 lines (39 loc) · 1.04 KB
/
json_storer.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
package data
import "encoding/json"
// JSONStorer allows storage of normal strings and json values into a map.
type JSONStorer map[string]string
// Clone does a deep copy of the JSONStorer.
func (js JSONStorer) Clone() JSONStorer {
j := make(JSONStorer, len(js))
for k, v := range js {
j[k] = v
}
return j
}
// Put puts a regular string into the map.
func (js JSONStorer) Put(key, value string) {
js[key] = value
}
// Get gets a regular string from the map.
func (js JSONStorer) Get(key string) (string, bool) {
ret, ok := js[key]
return ret, ok
}
// PutJSON serializes the value and stores it in the map.
func (js JSONStorer) PutJSON(key string, value interface{}) error {
jsMarsh, err := json.Marshal(value)
if err != nil {
return err
}
js[key] = string(jsMarsh)
return nil
}
// GetJSON deserializes the value from the map and stores it in intf.
func (js JSONStorer) GetJSON(key string, intf interface{}) (bool, error) {
ret, ok := js[key]
if !ok {
return false, nil
}
err := json.Unmarshal([]byte(ret), intf)
return true, err
}