-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
42 lines (38 loc) · 832 Bytes
/
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
package godash
import (
"bytes"
"encoding/json"
)
func StructToMap(srcStruct interface{}) (map[string]interface{}, error) {
dst := make(map[string]interface{})
srcBtyes, err := json.Marshal(srcStruct)
if err != nil {
return nil, err
}
decoder := json.NewDecoder(bytes.NewReader(srcBtyes))
decoder.UseNumber()
err = decoder.Decode(&dst)
if err != nil {
return nil, err
}
return dst, nil
}
func StructToMapStrict(srcStruct interface{}) (map[string]interface{}, error) {
dst := make(map[string]interface{})
srcBtyes, err := json.Marshal(srcStruct)
if err != nil {
return nil, err
}
decoder := json.NewDecoder(bytes.NewReader(srcBtyes))
decoder.UseNumber()
err = decoder.Decode(&dst)
if err != nil {
return nil, err
}
for k, v := range dst {
if nil == v {
delete(dst, k)
}
}
return dst, nil
}