-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathjson.go
64 lines (60 loc) · 1.2 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
package lambroll
import (
"encoding/json"
"log"
)
func isEmptyValue(value interface{}) bool {
switch v := value.(type) {
case nil:
return true
case string:
return v == ""
case bool:
return !v
case map[string]interface{}:
return len(v) == 0
case []interface{}:
return len(v) == 0
default:
return false
}
}
func omitEmptyValues(data interface{}) interface{} {
switch v := data.(type) {
case map[string]interface{}:
nonEmptyMap := make(map[string]interface{})
for key, value := range v {
nonEmptyValue := omitEmptyValues(value)
if !isEmptyValue(nonEmptyValue) {
nonEmptyMap[key] = nonEmptyValue
}
}
if len(nonEmptyMap) != 0 {
return nonEmptyMap
}
case []interface{}:
nonEmptyList := make([]interface{}, 0)
for _, value := range v {
nonEmptyValue := omitEmptyValues(value)
if !isEmptyValue(nonEmptyValue) {
nonEmptyList = append(nonEmptyList, nonEmptyValue)
}
}
if len(nonEmptyList) != 0 {
return nonEmptyList
}
default:
if !isEmptyValue(v) {
return v
}
}
return nil
}
func ToJSONString(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
log.Println("[warn] failed to marshal json:", err)
return ""
}
return string(b)
}