-
Notifications
You must be signed in to change notification settings - Fork 3
/
json.go
74 lines (58 loc) · 1.35 KB
/
json.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
65
66
67
68
69
70
71
72
73
74
package eventline
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"github.com/exograd/eventline/pkg/utils"
)
func JSONFields(value interface{}) (map[string]string, error) {
data, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("cannot encode value: %w", err)
}
d := json.NewDecoder(bytes.NewReader(data))
d.DisallowUnknownFields()
d.UseNumber()
var obj map[string]interface{}
if err := d.Decode(&obj); err != nil {
return nil, fmt.Errorf("cannot decode json data: %w", err)
}
fields := make(map[string]string)
jsonFields(obj, "", fields)
return fields, nil
}
func jsonFields(value interface{}, key string, fields map[string]string) {
switch v := value.(type) {
case map[string]interface{}:
for name, child := range v {
var childKey string
if key == "" {
childKey = name
} else {
childKey = key + "/" + name
}
jsonFields(child, childKey, fields)
}
case []interface{}:
for i, child := range v {
var childKey string
if key == "" {
childKey = strconv.Itoa(i)
} else {
childKey = key + "/" + strconv.Itoa(i)
}
jsonFields(child, childKey, fields)
}
case bool:
fields[key] = strconv.FormatBool(v)
case string:
fields[key] = v
case json.Number:
fields[key] = v.String()
case nil:
fields[key] = "null"
default:
utils.Panicf("unhandled json value %#v", value)
}
}