forked from buger/jsonparser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
411 lines (336 loc) · 9.18 KB
/
parser.go
File metadata and controls
411 lines (336 loc) · 9.18 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package jsonparser
import (
"bytes"
"errors"
"fmt"
"reflect"
"strconv"
"unsafe"
)
func tokenEnd(data []byte) int {
for i, c := range data {
switch c {
case ' ', '\n', '\r', '\t', ',', '}', ']':
return i
}
}
return -1
}
// Find position of next character which is not ' ', ',', '}' or ']'
func nextToken(data []byte, skipComma bool) int {
for i, c := range data {
switch c {
case ' ', '\n', '\r', '\t':
continue
case ',':
if !skipComma {
continue
} else {
return i
}
default:
return i
}
}
return -1
}
// Tries to find the end of string
// Support if string contains escaped quote symbols.
func stringEnd(data []byte) int {
for i, c := range data {
if c == '"' {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1 // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {
break // odd number of backslashes
}
j--
}
}
}
return -1
}
// Find end of the data structure, array or object.
// For array openSym and closeSym will be '[' and ']', for object '{' and '}'
func blockEnd(data []byte, openSym byte, closeSym byte) int {
level := 0
i := 0
ln := len(data)
for i < ln {
switch data[i] {
case '"': // If inside string, skip it
se := stringEnd(data[i+1:])
if se == -1 {
return -1
}
i += se
case openSym: // If open symbol, increase level
level++
case closeSym: // If close symbol, increase level
level--
// If we have returned to the original level, we're done
if level == 0 {
return i + 1
}
}
i++
}
return -1
}
func searchKeys(data []byte, keys ...string) int {
keyLevel := 0
level := 0
i := 0
ln := len(data)
lk := len(keys)
for i < ln {
switch data[i] {
case '"':
i++
keyBegin := i
strEnd := stringEnd(data[i:])
if strEnd == -1 {
return -1
}
i += strEnd
keyEnd := i - 1
valueOffset := nextToken(data[i:], true)
if valueOffset == -1 {
return -1
}
i += valueOffset
if i < ln &&
data[i] == ':' && // if string is a Key, and key level match
keyLevel == level-1 && // If key nesting level match current object nested level
keys[level-1] == unsafeBytesToString(data[keyBegin:keyEnd]) {
keyLevel++
// If we found all keys in path
if keyLevel == lk {
return i + 1
}
}
case '{':
level++
case '}':
level--
case '[':
// Do not search for keys inside arrays
arraySkip := blockEnd(data[i:], '[', ']')
i += arraySkip
}
i++
}
return -1
}
// Data types available in valid JSON data.
const (
NotExist = iota
String
Number
Object
Array
Boolean
Null
Unknown
)
/*
Get - Receives data structure, and key path to extract value from.
Returns:
`value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
`dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
`offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
`err` - If key not found or any other parsing issue it should return error. If key not found it also sets `dataType` to `NotExist`
Accept multiple keys to specify path to JSON value (in case of quering nested structures).
If no keys provided it will try to extract closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.
*/
func Get(data []byte, keys ...string) (value []byte, dataType int, offset int, err error) {
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return []byte{}, NotExist, -1, errors.New("Key path not found")
}
}
// Go to closest value
nO := nextToken(data[offset:], false)
if nO == -1 {
return []byte{}, NotExist, -1, errors.New("Malformed JSON error")
}
offset += nO
endOffset := offset
// if string value
if data[offset] == '"' {
dataType = String
if idx := stringEnd(data[offset+1:]); idx != -1 {
endOffset += idx + 1
} else {
return []byte{}, dataType, offset, errors.New("Value is string, but can't find closing '\"' symbol")
}
} else if data[offset] == '[' { // if array value
dataType = Array
// break label, for stopping nested loops
endOffset = blockEnd(data[offset:], '[', ']')
if endOffset == -1 {
return []byte{}, dataType, offset, errors.New("Value is array, but can't find closing ']' symbol")
}
endOffset += offset
} else if data[offset] == '{' { // if object value
dataType = Object
// break label, for stopping nested loops
endOffset = blockEnd(data[offset:], '{', '}')
if endOffset == -1 {
return []byte{}, dataType, offset, errors.New("Value looks like object, but can't find closing '}' symbol")
}
endOffset += offset
} else {
// Number, Boolean or None
end := tokenEnd(data[endOffset:])
if end == -1 {
return nil, dataType, offset, errors.New("Value looks like Number/Boolean/None, but can't find its end: ',' or '}' symbol")
}
value := unsafeBytesToString(data[offset : endOffset+end])
switch data[offset] {
case 't', 'f': // true or false
if (len(value) == 4 && value == "true") || (len(value) == 5 && value == "false") {
dataType = Boolean
} else {
return nil, Unknown, offset, errors.New("Unknown value type")
}
case 'u', 'n': // undefined or null
if len(value) == 4 && value == "null" {
dataType = Null
} else {
return nil, Unknown, offset, errors.New("Unknown value type")
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
dataType = Number
default:
return nil, Unknown, offset, errors.New("Unknown value type")
}
endOffset += end
}
value = data[offset:endOffset]
// Strip quotes from string values
if dataType == String {
value = value[1 : len(value)-1]
}
if dataType == Null {
value = []byte{}
}
return value, dataType, endOffset, nil
}
// ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`.
func ArrayEach(data []byte, cb func(value []byte, dataType int, offset int, err error), keys ...string) (err error) {
if len(data) == 0 {
return errors.New("Object is empty")
}
offset := 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return errors.New("Key path not found")
}
// Go to closest value
nO := nextToken(data[offset:], false)
if nO == -1 {
return errors.New("Malformed JSON")
}
offset += nO
if data[offset] != '[' {
return errors.New("Value is not array")
}
offset++
}
for true {
v, t, o, e := Get(data[offset:])
if o == 0 {
break
}
if t != NotExist {
cb(v, t, o, e)
}
if e != nil {
break
}
offset += o
}
return nil
}
// GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols.
func GetUnsafeString(data []byte, keys ...string) (val string, err error) {
v, _, _, e := Get(data, keys...)
if e != nil {
return "", e
}
return unsafeBytesToString(v), nil
}
// GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols
// If key data type do not match, it will return an error.
func GetString(data []byte, keys ...string) (val string, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return "", e
}
if t != String {
return "", fmt.Errorf("Value is not a number: %s", string(v))
}
// If no escapes return raw conten
if bytes.IndexByte(v, '\\') == -1 {
return string(v), nil
}
s, err := strconv.Unquote(`"` + unsafeBytesToString(v) + `"`)
return s, err
}
// GetFloat returns the value retrieved by `Get`, cast to a float64 if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return an error.
func GetFloat(data []byte, keys ...string) (val float64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
val, err = strconv.ParseFloat(unsafeBytesToString(v), 64)
return
}
// GetInt returns the value retrieved by `Get`, cast to a float64 if possible.
// If key data type do not match, it will return an error.
func GetInt(data []byte, keys ...string) (val int64, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return 0, e
}
if t != Number {
return 0, fmt.Errorf("Value is not a number: %s", string(v))
}
val, err = strconv.ParseInt(unsafeBytesToString(v), 10, 64)
return
}
// GetBoolean returns the value retrieved by `Get`, cast to a bool if possible.
// The offset is the same as in `Get`.
// If key data type do not match, it will return error.
func GetBoolean(data []byte, keys ...string) (val bool, err error) {
v, t, _, e := Get(data, keys...)
if e != nil {
return false, e
}
if t != Boolean {
return false, fmt.Errorf("Value is not a boolean: %s", string(v))
}
if v[0] == 't' {
val = true
} else {
val = false
}
return
}
// A hack until issue golang/go#2632 is fixed.
// See: https://github.com/golang/go/issues/2632
func unsafeBytesToString(data []byte) string {
h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
sh := reflect.StringHeader{Data: h.Data, Len: h.Len}
return *(*string)(unsafe.Pointer(&sh))
}