-
Notifications
You must be signed in to change notification settings - Fork 0
/
vanish.go
83 lines (67 loc) · 1.59 KB
/
vanish.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
77
78
79
80
81
82
83
package vanish
import (
"encoding/json"
"errors"
"reflect"
"strings"
)
func RemoveFields(jsonData []byte, fields []string) ([]byte, error) {
var i interface{}
// Try to check if string is JSON
err := json.Unmarshal(jsonData, &i)
if err != nil {
return nil, errors.New("the input data is not JSON format. Caused by: " + err.Error())
}
m, ok := i.(map[string]interface{})
if !ok {
return nil, errors.New("the input data is not JSON format")
}
return json.Marshal(rebuild(m, fields))
}
func rebuild(m map[string]interface{}, fields []string) map[string]interface{} {
res := make(map[string]interface{})
currents, childs := getCurrentRemoveFields(fields)
for _, field := range currents {
delete(m, field)
}
for key, val := range m {
valOf := reflect.ValueOf(val)
switch valOf.Kind() {
case reflect.Map:
{
if m, ok := val.(map[string]interface{}); ok {
res[key] = rebuild(m, childs)
}
}
case reflect.Slice, reflect.Array:
{
var slice []interface{}
for i := 0; i < valOf.Len(); i++ {
item := valOf.Index(i).Interface()
if m, ok := item.(map[string]interface{}); ok {
item = rebuild(m, childs)
}
slice = append(slice, item)
}
res[key] = slice
}
default:
res[key] = val
}
}
return res
}
// Get removable fields
func getCurrentRemoveFields(fields []string) ([]string, []string) {
var currents, childs []string
for _, f := range fields {
r := strings.SplitN(f, ".", 2)
switch len(r) {
case 1:
currents = append(currents, r[0])
case 2:
childs = append(childs, r[1])
}
}
return currents, childs
}