-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathjson.go
63 lines (53 loc) · 1.15 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
package xj2go
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
)
func jsonToLeafNodes(root, filename string) ([]leafNode, error) {
if root == "" {
root = "Result"
}
m, err := jsonFileToMap(root, filename)
if err != nil {
log.Fatal(err)
return nil, err
}
lns, err := leafNodes(m)
if err != nil {
log.Fatal(err)
return nil, err
}
return reLeafNodes(lns, root)
}
func jsonFileToMap(root, filename string) (map[string]interface{}, error) {
m := make(map[string]interface{})
val, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
if len(val) == 0 {
return m, nil
}
if val[0] == '[' {
val = []byte(`{"` + root + `":` + string(val) + `}`)
}
return jsonDecode(&m, &val)
}
func jsonBytesToMap(pkg, root string, b *[]byte) (map[string]interface{}, error) {
if root == "" {
root = "Result"
}
m := make(map[string]interface{})
if (*b)[0] == '[' {
*b = []byte(`{"` + root + `":` + string(*b) + `}`)
}
return jsonDecode(&m, b)
}
func jsonDecode(m *map[string]interface{}, b *[]byte) (map[string]interface{}, error) {
buf := bytes.NewReader(*b)
dec := json.NewDecoder(buf)
err := dec.Decode(m)
return *m, err
}