forked from nuptzp/utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonparse.go
114 lines (95 loc) · 2.15 KB
/
jsonparse.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package utils
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
)
type JsonParser struct {
}
func NewJsonParser() *JsonParser {
return &JsonParser{}
}
func (self *JsonParser) Load(fileOrString string, v interface{}) error {
data, err := ioutil.ReadFile(fileOrString)
if err != nil {
data = []byte(fileOrString)
}
err = json.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}
func (self *JsonParser) Save(fileName string, v interface{}) (err error) {
var data []byte
switch v.(type) {
case string:
data = []byte(v.(string))
default:
data, err = json.Marshal(v)
if err != nil {
return err
}
}
err = ioutil.WriteFile(fileName, data, os.ModeAppend)
if err != nil {
return err
}
return nil
}
func (self *JsonParser) Marshal(v interface{}) ([]byte, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
return data, nil
}
type JsonReader struct {
}
func NewJsonReader() *JsonReader {
return &JsonReader{}
}
func (self *JsonReader) Load(fileOrString string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(fileOrString)
if err != nil {
data = []byte(fileOrString)
}
jsonDecoder := json.NewDecoder(strings.NewReader(string(data)))
dataMap := map[string]interface{}{}
err = jsonDecoder.Decode(&dataMap)
if err != nil {
return nil, err
}
kvMap := getMap(dataMap)
return kvMap, nil
}
func getMap(dataMap map[string]interface{}) map[string]interface{} {
kvMap := make(map[string]interface{})
for key, value := range dataMap {
switch value.(type) {
case map[string]interface{}:
subkvMap := getMap(value.(map[string]interface{}))
tempMap := fmtKVMap(key, subkvMap)
appendMap(kvMap, tempMap)
default:
kvMap[key] = value
}
}
return kvMap
}
func fmtKVMap(key string, subkvMap map[string]interface{}) map[string]interface{} {
retMap := make(map[string]interface{})
for subKey, value := range subkvMap {
keyString := fmt.Sprintf("%s.%s", key, subKey)
retMap[keyString] = value
}
return retMap
}
func appendMap(addedMap, addMap map[string]interface{}) map[string]interface{} {
for key, value := range addMap {
addedMap[key] = value
}
return addedMap
}