-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsonparse.go
More file actions
93 lines (82 loc) · 1.86 KB
/
Copy pathjsonparse.go
File metadata and controls
93 lines (82 loc) · 1.86 KB
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
package jsonparse
import (
"encoding/json"
"fmt"
"strings"
)
type JsonData map[string]interface{}
func setJsonData(m map[string]interface{}, val interface{}, keys []string) error {
length := len(keys)
if length == 0 {
return fmt.Errorf("The keys is empty!")
}
key := keys[0]
if length == 1 {
m[key] = val
} else {
m1, ok := m[key].(map[string]interface{})
if !ok {
m1 = make(map[string]interface{})
}
setJsonData(m1, val, keys[1:])
m[key] = m1
}
return nil
}
type jsonData struct {
jd *JsonData
keys []string
}
func (jsd *jsonData) Set(value interface{}) error {
return jsd.jd.Set(value, jsd.keys...)
}
func (jsd *jsonData) Get() (interface{}, error) {
return jsd.jd.Get(jsd.keys...)
}
func (jd *JsonData) Key(keys ...string) *jsonData {
return &jsonData{jd: jd, keys: keys}
}
func (jd *JsonData) Set(value interface{}, keys ...string) error {
if len(keys) == 0 {
m, ok := value.(map[string]interface{})
if ok {
*jd = m
return nil
} else {
return fmt.Errorf("The keys is empty and the value is not a json map!")
}
}
val := *jd
err := setJsonData(val, value, keys)
*jd = val
return err
}
func (jd *JsonData) Get(keys ...string) (interface{}, error) {
val := *jd
length := len(keys)
if length == 0 {
return val, nil
}
for i, key := range keys {
ret, ok := val[key]
if !ok {
return nil, fmt.Errorf("There's no key <%s> exist in the json data", strings.Join(keys[:i+1], "."))
}
if i == length-1 {
return ret, nil
}
val, ok = ret.(map[string]interface{})
if ok {
continue
} else {
return nil, fmt.Errorf("The key <%s> is not a json map,value: %v", strings.Join(keys[:i+1], "."), ret)
}
}
return nil, fmt.Errorf("Unexcept operation...")
}
func (jd *JsonData) Marshal() ([]byte, error) {
return json.Marshal(*jd)
}
func (jd *JsonData) Unmarshal(data []byte) error {
return json.Unmarshal(data, jd)
}