-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
125 lines (114 loc) · 2.5 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
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
115
116
117
118
119
120
121
122
123
124
125
package libjson
import (
jsoniter "github.com/json-iterator/go"
"github.com/lwpyr/goscript/common"
"strconv"
"unicode"
)
func JsonMarshal(m *common.Memory, stk *common.Stack) {
bytes, err := jsoniter.Marshal(stk.Top())
if err != nil {
panic(err)
}
stk.ReturnValue(bytes)
}
func JsonUnmarshal(m *common.Memory, stk *common.Stack) {
bytes := (stk.TopIndex(1)).([]byte)
T := (stk.Top()).(*common.DataType)
stk.Pop()
iter := jsoniter.ConfigFastest.BorrowIterator(bytes)
defer jsoniter.ConfigFastest.ReturnIterator(iter)
stk.ReturnValue(T.Unmarshal(iter))
}
func JsonObject(m *common.Memory, stk *common.Stack) {
bytes := (stk.Top()).([]byte)
val := map[string]interface{}{}
err := jsoniter.Unmarshal(bytes, &val)
if err != nil {
panic(err)
}
stk.ReturnValue(val)
}
func JsonPath(m *common.Memory, stk *common.Stack) {
jsonObject := stk.TopIndex(1)
path := (stk.Top()).(string)
p := NewParser(path)
for tokeType, token := p.next(); tokeType != eof; tokeType, token = p.next() {
if tokeType == selector {
jsonObject = jsonObject.(map[string]interface{})[token.(string)]
} else {
jsonObject = jsonObject.([]interface{})[token.(int64)]
}
}
stk.ReturnValue(jsonObject)
}
type simpleParser struct {
idx int
path string
}
const (
selector = iota
index
eof
)
func NewParser(path string) *simpleParser {
return &simpleParser{
idx: 0,
path: path,
}
}
func (s *simpleParser) next() (int, interface{}) {
if s.idx >= len(s.path) {
return eof, nil
}
for s.idx < len(s.path) && s.path[s.idx] == ' ' {
s.idx++
}
if s.idx == 0 {
if s.path[0] != '$' {
panic("invalid path")
}
s.idx++
}
if s.path[s.idx] == '.' {
s.idx++
if s.idx == len(s.path) {
panic("invalid path")
}
begin := s.idx
for s.idx < len(s.path) && s.path[s.idx] != '.' && s.path[s.idx] != '[' {
if s.path[s.idx] == ' ' {
panic("invalid path")
}
s.idx++
}
return selector, s.path[begin:s.idx]
} else if s.path[s.idx] == '[' {
s.idx++
for s.idx < len(s.path) && s.path[s.idx] == ' ' {
s.idx++
}
if s.idx == len(s.path) {
panic("invalid path")
}
begin := s.idx
for s.idx < len(s.path) && unicode.IsDigit(rune(s.path[s.idx])) {
s.idx++
}
end := s.idx
if begin == end {
panic("invalid path")
}
for s.idx < len(s.path) && s.path[s.idx] == ' ' {
s.idx++
}
if s.idx == len(s.path) || s.path[s.idx] != ']' {
panic("invalid path")
}
s.idx++
num, _ := strconv.ParseInt(s.path[begin:end], 10, 64)
return index, num
} else {
panic("invalid path")
}
}