-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
json.go
76 lines (71 loc) · 1.3 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
75
76
package sdkclient
import (
"encoding/json"
"strings"
)
func marshalJSON(v interface{}, camelCase bool) ([]byte, error) {
if v == nil {
return nil, nil
}
if !camelCase {
return json.Marshal(v)
}
b, err := json.Marshal(v)
if err != nil {
return nil, err
}
switch b[0] {
case '{':
m := map[string]any{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
walkMap(m, toCamelCase)
return json.Marshal(m)
case '[':
a := []any{}
if err := json.Unmarshal(b, &a); err != nil {
return nil, err
}
walkArray(a, toCamelCase)
return json.Marshal(a)
default:
return b, nil
}
}
func toCamelCase(s string) string {
if len(s) == 0 {
return s
}
return strings.ToLower(s[:1]) + s[1:]
}
func walkMap(m map[string]interface{}, fn func(string) string) {
for key, value := range m {
delete(m, key)
newKey := key
if fn != nil {
newKey = fn(key)
}
if value != nil {
m[newKey] = value
}
switch value := value.(type) {
case map[string]any:
walkMap(value, fn)
case []interface{}:
walkArray(value, fn)
default:
}
}
}
func walkArray(a []interface{}, fn func(string) string) {
for _, value := range a {
switch value := value.(type) {
case map[string]interface{}:
walkMap(value, fn)
case []interface{}:
walkArray(value, fn)
default:
}
}
}