forked from buger/jsonparser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
1141 lines (964 loc) · 26.3 KB
/
parser.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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jsonparser
import (
"bytes"
"fmt"
"math"
"strconv"
"strings"
)
// How much stack space to allocate for unescaping JSON strings; if a string longer
// than this needs to be escaped, it will result in a heap allocation
const unescapeStackBufSize = 64
func tokenEnd(data []byte) int {
for i, c := range data {
switch c {
case ' ', '\n', '\r', '\t', ',', '}', ']':
return i
}
}
return len(data)
}
func findTokenStart(data []byte, token byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case token:
return i
case '[', '{':
return 0
}
}
return 0
}
func findKeyStart(data []byte, key string) (int, error) {
i := 0
ln := len(data)
if ln > 0 && (data[0] == '{' || data[0] == '[') {
i = 1
}
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
if ku, err := Unescape(StringToBytes(key), stackbuf[:]); err == nil {
key = bytesToString(&ku)
}
for i < ln {
switch data[i] {
case '"':
i++
keyBegin := i
strEnd, keyEscaped := stringEnd(data[i:])
if strEnd == -1 {
break
}
i += strEnd
keyEnd := i - 1
valueOffset := nextToken(data[i:])
if valueOffset == -1 {
break
}
i += valueOffset
// if string is a key, and key level match
k := data[keyBegin:keyEnd]
// for unescape: if there are no escape sequences, this is cheap; if there are, it is a
// bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize
if keyEscaped {
if ku, err := Unescape(k, stackbuf[:]); err != nil {
break
} else {
k = ku
}
}
if data[i] == ':' && len(key) == len(k) && bytesToString(&k) == key {
return keyBegin - 1, nil
}
case '[':
i = blockEnd(data[i:], data[i], ']') + i
case '{':
i = blockEnd(data[i:], data[i], '}') + i
}
i++
}
return -1, KeyPathNotFoundError(0)
}
func tokenStart(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case '\n', '\r', '\t', ',', '{', '[':
return i
}
}
return 0
}
// Find position of next character which is not whitespace
func nextToken(data []byte) int {
for i, c := range data {
switch c {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
}
// Find position of last character which is not whitespace
func lastToken(data []byte) int {
for i := len(data) - 1; i >= 0; i-- {
switch data[i] {
case ' ', '\n', '\r', '\t':
continue
default:
return i
}
}
return -1
}
// Tries to find the end of string
// Support if string contains escaped quote symbols.
func stringEnd(data []byte) (int, bool) {
escaped := false
for i, c := range data {
if c == '"' {
if !escaped {
return i + 1, false
} else {
j := i - 1
for {
if j < 0 || data[j] != '\\' {
return i + 1, true // even number of backslashes
}
j--
if j < 0 || data[j] != '\\' {
break // odd number of backslashes
}
j--
}
}
} else if c == '\\' {
escaped = true
}
}
return -1, escaped
}
// 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)
if lk == 0 {
return 0
}
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
for i < ln {
switch data[i] {
case '"':
i++
keyBegin := i
strEnd, keyEscaped := stringEnd(data[i:])
if strEnd == -1 {
return -1
}
i += strEnd
keyEnd := i - 1
valueOffset := nextToken(data[i:])
if valueOffset == -1 {
return -1
}
i += valueOffset
// if string is a key, and key level match
if data[i] == ':' && keyLevel == level-1 {
key := data[keyBegin:keyEnd]
// for unescape: if there are no escape sequences, this is cheap; if there are, it is a
// bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize
var keyUnesc []byte
if !keyEscaped {
keyUnesc = key
} else if ku, err := Unescape(key, stackbuf[:]); err != nil {
return -1
} else {
keyUnesc = ku
}
if equalStr(&keyUnesc, keys[level-1]) {
keyLevel++
// If we found all keys in path
if keyLevel == lk {
return i + 1
}
}
} else {
i--
}
case '{':
level++
case '}':
level--
if level == keyLevel {
keyLevel--
}
case '[':
// If we want to get array element by index
if keyLevel == level && keys[level][0] == '[' {
aIdx, err := strconv.Atoi(keys[level][1 : len(keys[level])-1])
if err != nil {
return -1
}
var curIdx int
var valueFound []byte
var valueOffset int
var curI = i
ArrayEach(data[i:], func(value []byte, dataType ValueType, startOffset int, endOffset int, err error) {
if curIdx == aIdx {
valueFound = value
valueOffset = startOffset
if dataType == String {
valueOffset = valueOffset
valueFound = data[curI+valueOffset : curI+valueOffset+len(value)]
}
}
curIdx += 1
})
if valueFound == nil {
return -1
} else {
subIndex := searchKeys(valueFound, keys[level+1:]...)
if subIndex < 0 {
return -1
}
return i + valueOffset + subIndex
}
} else {
// Do not search for keys inside arrays
if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 {
return -1
} else {
i += arraySkip - 1
}
}
}
i++
}
return -1
}
var bitwiseFlags []int64
func init() {
for i := 0; i < 63; i++ {
bitwiseFlags = append(bitwiseFlags, int64(math.Pow(2, float64(i))))
}
}
func sameTree(p1, p2 []string) bool {
minLen := len(p1)
if len(p2) < minLen {
minLen = len(p2)
}
for pi_1, p_1 := range p1[:minLen] {
if p2[pi_1] != p_1 {
return false
}
}
return true
}
func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]string) int {
var pathFlags int64
var level, pathsMatched, i int
ln := len(data)
var maxPath int
for _, p := range paths {
if len(p) > maxPath {
maxPath = len(p)
}
}
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
pathsBuf := make([]string, maxPath)
for i < ln {
switch data[i] {
case '"':
i++
keyBegin := i
strEnd, keyEscaped := stringEnd(data[i:])
if strEnd == -1 {
return -1
}
i += strEnd
keyEnd := i - 1
valueOffset := nextToken(data[i:])
if valueOffset == -1 {
return -1
}
i += valueOffset
// if string is a key, and key level match
if data[i] == ':' {
match := -1
key := data[keyBegin:keyEnd]
// for unescape: if there are no escape sequences, this is cheap; if there are, it is a
// bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize
var keyUnesc []byte
if !keyEscaped {
keyUnesc = key
} else if ku, err := Unescape(key, stackbuf[:]); err != nil {
return -1
} else {
keyUnesc = ku
}
if maxPath >= level {
if level < 1 {
cb(-1, nil, Unknown, MalformedJsonError(valueOffset))
return -1
}
pathsBuf[level-1] = bytesToString(&keyUnesc)
for pi, p := range paths {
if len(p) != level || pathFlags&bitwiseFlags[pi+1] != 0 || !equalStr(&keyUnesc, p[level-1]) || !sameTree(p, pathsBuf[:level]) {
continue
}
match = pi
i++
pathsMatched++
pathFlags |= bitwiseFlags[pi+1]
v, dt, _, of, e := Get(data[i:])
cb(pi, v, dt, addToErrorOffset(e, i))
if of != -1 {
i += of
}
if pathsMatched == len(paths) {
break
}
}
if pathsMatched == len(paths) {
return i
}
}
if match == -1 {
tokenOffset := nextToken(data[i+1:])
i += tokenOffset
if data[i] == '{' {
blockSkip := blockEnd(data[i:], '{', '}')
i += blockSkip + 1
}
}
switch data[i] {
case '{', '}', '[', '"':
i--
}
} else {
i--
}
case '{':
level++
case '}':
level--
case '[':
var arrIdxFlags int64
var pIdxFlags int64
if level < 0 {
cb(-1, nil, Unknown, MalformedJsonError(0))
return -1
}
for pi, p := range paths {
if len(p) < level+1 || pathFlags&bitwiseFlags[pi+1] != 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) {
continue
}
aIdx, _ := strconv.Atoi(p[level][1 : len(p[level])-1])
arrIdxFlags |= bitwiseFlags[aIdx+1]
pIdxFlags |= bitwiseFlags[pi+1]
}
if arrIdxFlags > 0 {
level++
var curIdx int
arrOff, _ := ArrayEach(data[i:], func(value []byte, dataType ValueType, startOffset int, endOffset int, err error) {
if arrIdxFlags&bitwiseFlags[curIdx+1] != 0 {
for pi, p := range paths {
if pIdxFlags&bitwiseFlags[pi+1] != 0 {
aIdx, _ := strconv.Atoi(p[level-1][1 : len(p[level-1])-1])
if curIdx == aIdx {
of := searchKeys(value, p[level:]...)
pathsMatched++
pathFlags |= bitwiseFlags[pi+1]
if of != -1 {
v, dt, _, _, e := Get(value[of:])
cb(pi, v, dt, addToErrorOffset(e, of))
}
}
}
}
}
curIdx += 1
})
if pathsMatched == len(paths) {
return i
}
i += arrOff - 1
} else {
// Do not search for keys inside arrays
if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 {
return -1
} else {
i += arraySkip - 1
}
}
case ']':
level--
}
i++
}
return -1
}
// Data types available in valid JSON data.
type ValueType int
const (
NotExist = ValueType(iota)
String
Number
Object
Array
Boolean
Null
Unknown
)
func (vt ValueType) String() string {
switch vt {
case NotExist:
return "non-existent"
case String:
return "string"
case Number:
return "number"
case Object:
return "object"
case Array:
return "array"
case Boolean:
return "boolean"
case Null:
return "null"
default:
return "unknown"
}
}
var (
trueLiteral = []byte("true")
falseLiteral = []byte("false")
nullLiteral = []byte("null")
)
func createInsertComponent(keys []string, setValue []byte, comma, object bool) []byte {
var buffer bytes.Buffer
if comma {
buffer.WriteString(",")
}
if object {
buffer.WriteString("{")
}
buffer.WriteString("\"")
buffer.WriteString(keys[0])
buffer.WriteString("\":")
for i := 1; i < len(keys); i++ {
buffer.WriteString("{\"")
buffer.WriteString(keys[i])
buffer.WriteString("\":")
}
buffer.Write(setValue)
buffer.WriteString(strings.Repeat("}", len(keys)-1))
if object {
buffer.WriteString("}")
}
return buffer.Bytes()
}
/*
Del - Receives existing data structure, path to delete.
Returns:
`data` - return modified data
*/
func Delete(data []byte, keys ...string) []byte {
lk := len(keys)
if lk == 0 {
return data[:0]
}
array := false
if len(keys[lk-1]) > 0 && string(keys[lk-1][0]) == "[" {
array = true
}
var startOffset, keyOffset int
endOffset := len(data)
var err error
if !array {
if len(keys) > 1 {
_, _, startOffset, endOffset, err = internalGet(data, keys[:lk-1]...)
if isKeyPathNotFoundError(err) {
// problem parsing the data
return data
}
}
keyOffset, err = findKeyStart(data[startOffset:endOffset], keys[lk-1])
if isKeyPathNotFoundError(err) {
// problem parsing the data
return data
}
keyOffset += startOffset
_, _, _, subEndOffset, _ := internalGet(data[startOffset:endOffset], keys[lk-1])
endOffset = startOffset + subEndOffset
tokEnd := tokenEnd(data[endOffset:])
tokStart := findTokenStart(data[:keyOffset], ","[0])
if data[endOffset+tokEnd] == ","[0] {
endOffset += tokEnd + 1
} else if data[endOffset+tokEnd] == "}"[0] && data[tokStart] == ","[0] {
keyOffset = tokStart
}
} else {
_, _, keyOffset, endOffset, err = internalGet(data, keys...)
if isKeyPathNotFoundError(err) {
// problem parsing the data
return data
}
tokEnd := tokenEnd(data[endOffset:])
tokStart := findTokenStart(data[:keyOffset], ","[0])
if data[endOffset+tokEnd] == ","[0] {
endOffset += tokEnd + 1
} else if data[endOffset+tokEnd] == "]"[0] && data[tokStart] == ","[0] {
keyOffset = tokStart
}
}
data = append(data[:keyOffset], data[endOffset:]...)
return data
}
/*
Set - Receives existing data structure, path to set, and data to set at that key.
Returns:
`value` - modified byte array
`err` - On any parsing error
*/
func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) {
// ensure keys are set
if len(keys) == 0 {
return nil, KeyPathNotFoundError(0)
}
_, _, startOffset, endOffset, err := internalGet(data, keys...)
if err != nil {
if !isKeyPathNotFoundError(err) {
// problem parsing the data
return nil, err
}
// full path doesnt exist
// does any subpath exist?
var depth int
for i := range keys {
_, _, start, end, sErr := internalGet(data, keys[:i+1]...)
if sErr != nil {
break
} else {
endOffset = end
startOffset = start
depth++
}
}
comma := true
object := false
if endOffset == -1 {
firstToken := nextToken(data)
// We can't set a top-level key if data isn't an object
if len(data) == 0 || data[firstToken] != '{' {
return nil, KeyPathNotFoundError(firstToken)
}
// Don't need a comma if the input is an empty object
secondToken := firstToken + 1 + nextToken(data[firstToken+1:])
if data[secondToken] == '}' {
comma = false
}
// Set the top level key at the end (accounting for any trailing whitespace)
// This assumes last token is valid like '}', could check and return error
endOffset = lastToken(data)
}
depthOffset := endOffset
if depth != 0 {
// if subpath is a non-empty object, add to it
if data[startOffset] == '{' && data[startOffset+1+nextToken(data[startOffset+1:])] != '}' {
depthOffset--
startOffset = depthOffset
// otherwise, over-write it with a new object
} else {
comma = false
object = true
}
} else {
startOffset = depthOffset
}
value = append(data[:startOffset], append(createInsertComponent(keys[depth:], setValue, comma, object), data[depthOffset:]...)...)
} else {
// path currently exists
startComponent := data[:startOffset]
endComponent := data[endOffset:]
value = make([]byte, len(startComponent)+len(endComponent)+len(setValue))
newEndOffset := startOffset + len(setValue)
copy(value[0:startOffset], startComponent)
copy(value[startOffset:newEndOffset], setValue)
copy(value[newEndOffset:], endComponent)
}
return value, nil
}
func getType(data []byte, offset int) ([]byte, ValueType, int, error) {
var dataType ValueType
endOffset := offset
// if string value
if data[offset] == '"' {
dataType = String
if idx, _ := stringEnd(data[offset+1:]); idx != -1 {
endOffset += idx + 1
} else {
return nil, dataType, offset, MalformedStringError(offset)
}
} else if data[offset] == '[' { // if array value
dataType = Array
// break label, for stopping nested loops
endOffset = blockEnd(data[offset:], '[', ']')
if endOffset == -1 {
return nil, dataType, offset, MalformedArrayError(offset)
}
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 nil, dataType, offset, MalformedObjectError(offset)
}
endOffset += offset
} else {
// Number, Boolean or None
end := tokenEnd(data[endOffset:])
if end == -1 {
return nil, dataType, offset, MalformedValueError(offset)
}
value := data[offset : endOffset+end]
switch data[offset] {
case 't', 'f': // true or false
if bytes.Equal(value, trueLiteral) || bytes.Equal(value, falseLiteral) {
dataType = Boolean
} else {
return nil, Unknown, offset, UnknownValueTypeError(offset)
}
case 'u', 'n': // undefined or null
if bytes.Equal(value, nullLiteral) {
dataType = Null
} else {
return nil, Unknown, offset, UnknownValueTypeError(offset)
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
dataType = Number
default:
return nil, Unknown, offset, UnknownValueTypeError(offset)
}
endOffset += end
}
return data[offset:endOffset], dataType, endOffset, nil
}
/*
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 ValueType, offsetStart int, offsetEnd int, err error) {
a, b, c, d, e := internalGet(data, keys...)
return a, b, c, d, e
}
func internalGet(data []byte, keys ...string) (value []byte, dataType ValueType, offset, endOffset int, err error) {
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return nil, NotExist, -1, -1, KeyPathNotFoundError(0)
}
}
// Go to closest value
nO := nextToken(data[offset:])
if nO == -1 {
return nil, NotExist, offset, -1, MalformedJsonError(offset)
}
offset += nO
value, dataType, endOffset, err = getType(data, offset)
if err != nil {
return value, dataType, offset, endOffset, err
}
// Strip quotes from string values
if dataType == String {
value = value[1 : len(value)-1]
}
return value, dataType, offset, 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 ValueType, startOffset int, endOffset int, err error), keys ...string) (offset int, err error) {
if len(data) == 0 {
return -1, MalformedObjectError(0)
}
offset = 1
if len(keys) > 0 {
if offset = searchKeys(data, keys...); offset == -1 {
return offset, KeyPathNotFoundError(0)
}
// Go to closest value
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError(offset)
}
offset += nO
if data[offset] != '[' {
return offset, MalformedArrayError(offset)
}
offset++
}
nO := nextToken(data[offset:])
if nO == -1 {
return offset, MalformedJsonError(offset)
}
offset += nO
if data[offset] == ']' {
return offset, nil
}
for true {
v, t, os, o, e := Get(data[offset:])
if e != nil {
return offset, addToErrorOffset(e, offset)
}
if o == 0 {
break
}
if t != NotExist {
cb(v, t, offset+os, offset+o, e)
}
if e != nil {
break
}
offset += o
skipToToken := nextToken(data[offset:])
if skipToToken == -1 {
return offset, MalformedArrayError(offset)
}
offset += skipToToken
if data[offset] == ']' {
break
}
if data[offset] != ',' {
return offset, MalformedArrayError(offset)
}
offset++
}
return offset, nil
}
// ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, startOffset int, endOffset int, valueStartOffset int) error, keys... string) (err error) {
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
offset := 0
// Descend to the desired key, if requested
if len(keys) > 0 {
if off := searchKeys(data, keys...); off == -1 {
return KeyPathNotFoundError(offset)
} else {
offset = off
}
}
// Validate and skip past opening brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedObjectError(offset)
} else if offset += off; data[offset] != '{' {
return MalformedObjectError(offset)
} else {
offset++
}
// Skip to the first token inside the object, or stop if we find the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError(offset)
} else if offset += off; data[offset] == '}' {
return nil
}
// Loop pre-condition: data[offset] points to what should be either the next entry's key, or the closing brace (if it's anything else, the JSON is malformed)
for offset < len(data) {
// Step 1: find the next key
var key []byte
var objectStartOffset = offset
// Check what the the next token is: start of string, end of object, or something else (error)
switch data[offset] {
case '"':
offset++ // accept as string and skip opening quote
case '}':
return nil // we found the end of the object; stop and return success
default:
return MalformedObjectError(offset)
}
// Find the end of the key string
var keyEscaped bool
if off, esc := stringEnd(data[offset:]); off == -1 {
return MalformedJsonError(offset)
} else {
key, keyEscaped = data[offset:offset+off-1], esc
offset += off
}
// Unescape the string if needed
if keyEscaped {
if keyUnescaped, err := Unescape(key, stackbuf[:]); err != nil {
return MalformedStringEscapeError(offset)
} else {
key = keyUnescaped
}
}
// Step 2: skip the colon
if off := nextToken(data[offset:]); off == -1 {
return MalformedJsonError(offset)
} else if offset += off; data[offset] != ':' {
return MalformedJsonError(offset)
} else {
offset++
}
// Step 3: find the associated value, then invoke the callback
if value, valueType, valueStartOffset, off, err := Get(data[offset:]); err != nil {
return addToErrorOffset(err, offset)
} else if err := callback(key, value, valueType, objectStartOffset, offset+off, offset+valueStartOffset); err != nil { // Invoke the callback here!
return addToErrorOffset(err, offset)
} else {
offset += off
}
// Step 4: skip over the next comma to the following token, or stop if we hit the ending brace
if off := nextToken(data[offset:]); off == -1 {
return MalformedArrayError(offset)
} else {
offset += off
switch data[offset] {