-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.go
91 lines (78 loc) · 1.94 KB
/
tree.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
package qjson
// JSONTree represent full json
type JSONTree struct {
Root *Node
}
/* tree methods */
// IsNull tell node is null or not
func (tree *JSONTree) IsNull() bool {
return tree.Root == nil || tree.Root.IsNull()
}
// MarshalJSON json marshaller
func (tree *JSONTree) MarshalJSON() ([]byte, error) {
return tree.Root.MarshalJSON()
}
// UnmarshalJSON json unmarshaller
func (tree *JSONTree) UnmarshalJSON(data []byte) (err error) {
var tree1 *JSONTree
if tree1, err = Decode(data); err != nil {
return err
}
*tree = *tree1
return
}
// JSONString tree to string
func (tree *JSONTree) JSONString() string {
return string(JSONMarshalWithPanic(tree))
}
// JSONIndentString tree to string with indent
func (tree *JSONTree) JSONIndentString() string {
return string(JSONIndentMarshalWithPanic(tree))
}
// ColorfulMarshal print json with color
func (tree *JSONTree) ColorfulMarshal() []byte {
return new(Formatter).Format(tree)
}
// ColorfulMarshalWithIndent print json with indent
func (tree *JSONTree) ColorfulMarshalWithIndent() []byte {
return NewFormatter().Format(tree)
}
/* tree generator */
func makeNewTree() *JSONTree {
return &JSONTree{Root: CreateNode()}
}
// Find json node/nodes by path selector
func (tree *JSONTree) Find(path string) *Node {
p, ok := makeStPath(path)
if !ok {
return nil
}
return findNode(tree.Root, p)
}
// Remove json node
func (tree *JSONTree) Remove(path string) {
paths, ok := makeStPath(path)
if !ok {
return
}
if len(paths) == 0 {
return
}
if node := findNode(tree.Root, paths[:len(paths)-1]); node != nil {
lastKey := paths[len(paths)-1]
switch node.Type {
case Object:
node.RemoveObjectElemByKey(lastKey.Name)
case Array:
if lastKey.isInteger() {
node.RemoveArrayElemByIndex(lastKey.asInteger())
} else if lastKey.isArrayElemSelector() {
node.clearArray()
}
}
}
}
// Equal two json tree
func (tree *JSONTree) Equal(t2 *JSONTree) bool {
return tree.Root.Equal(t2.Root)
}