/
jsonkeys.go
73 lines (67 loc) · 1.67 KB
/
jsonkeys.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
package main
import (
"encoding/json"
"fmt"
"github.com/tidwall/gjson"
"io/ioutil"
"os"
"reflect"
"regexp"
"strings"
)
func iterate(data interface{}) interface{} {
if reflect.ValueOf(data).Kind() == reflect.Slice {
d := reflect.ValueOf(data)
tmpData := make([]interface{}, d.Len())
returnSlice := make([]interface{}, d.Len())
for i := 0; i < d.Len(); i++ {
tmpData[i] = d.Index(i).Interface()
}
for i, v := range tmpData {
returnSlice[i] = iterate(v)
}
return returnSlice
} else if reflect.ValueOf(data).Kind() == reflect.Map {
d := reflect.ValueOf(data)
tmpData := make(map[string]interface{})
for _, k := range d.MapKeys() {
match, _ := regexp.MatchString("$", k.String())
typeOfValue := reflect.TypeOf(d.MapIndex(k).Interface()).Kind()
if match {
newKey := strings.Replace(k.String(), "$", "", -1)
if typeOfValue == reflect.Map || typeOfValue == reflect.Slice {
tmpData[newKey] = iterate(d.MapIndex(k).Interface())
} else {
tmpData[newKey] = d.MapIndex(k).Interface()
}
} else {
fmt.Println("debug")
if typeOfValue == reflect.Map || typeOfValue == reflect.Slice {
tmpData[k.String()] = iterate(d.MapIndex(k).Interface())
} else {
tmpData[k.String()] = d.MapIndex(k).Interface()
}
}
}
return tmpData
}
return data
}
func main() {
file, e := ioutil.ReadFile("./nested.json")
if e != nil {
fmt.Printf("File error: %v\n", e)
os.Exit(1)
}
myJSON := string(file)
m, ok := gjson.Parse(myJSON).Value().(map[string]interface{})
if !ok {
fmt.Println("Error")
}
newM := iterate(m)
jsonBytes, err := json.Marshal(newM)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(jsonBytes))
}