-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathjson_flattener.go
70 lines (63 loc) · 1.56 KB
/
json_flattener.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
package json
import (
"fmt"
"strconv"
)
type JSONFlattener struct {
Fields map[string]interface{}
}
// FlattenJSON flattens nested maps/interfaces into a fields map (ignoring bools and string)
func (f *JSONFlattener) FlattenJSON(
fieldname string,
v interface{}) error {
if f.Fields == nil {
f.Fields = make(map[string]interface{})
}
return f.FullFlattenJSON(fieldname, v, false, false)
}
// FullFlattenJSON flattens nested maps/interfaces into a fields map (including bools and string)
func (f *JSONFlattener) FullFlattenJSON(fieldName string, v interface{}, convertString, convertBool bool) error {
if f.Fields == nil {
f.Fields = make(map[string]interface{})
}
switch t := v.(type) {
case map[string]interface{}:
for fieldKey, fieldVal := range t {
if fieldName != "" {
fieldKey = fieldName + "_" + fieldKey
}
err := f.FullFlattenJSON(fieldKey, fieldVal, convertString, convertBool)
if err != nil {
return err
}
}
case []interface{}:
for i, fieldVal := range t {
fieldKey := strconv.Itoa(i)
if fieldName != "" {
fieldKey = fieldName + "_" + fieldKey
}
err := f.FullFlattenJSON(fieldKey, fieldVal, convertString, convertBool)
if err != nil {
return err
}
}
case float64:
f.Fields[fieldName] = t
case string:
if !convertString {
return nil
}
f.Fields[fieldName] = v.(string)
case bool:
if !convertBool {
return nil
}
f.Fields[fieldName] = v.(bool)
case nil:
return nil
default:
return fmt.Errorf("json flattener: got unexpected type %T with value %v (%s)", t, t, fieldName)
}
return nil
}