forked from yunionio/jsonutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonutils.go
594 lines (549 loc) · 12.4 KB
/
jsonutils.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
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jsonutils
import (
"bytes"
"reflect"
"strconv"
"strings"
"time"
"unicode/utf8"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/gotypes"
"yunion.io/x/pkg/sortedmap"
)
type JSONObject interface {
gotypes.ISerializable
parse(str []byte, offset int) (int, error)
writeSource
// String() string
PrettyString() string
prettyString(level int) string
YAMLString() string
QueryString() string
_queryString(key string) string
Contains(keys ...string) bool
ContainsIgnoreCases(keys ...string) bool
Get(keys ...string) (JSONObject, error)
GetIgnoreCases(keys ...string) (JSONObject, error)
GetAt(i int, keys ...string) (JSONObject, error)
Int(keys ...string) (int64, error)
Float(keys ...string) (float64, error)
Bool(keys ...string) (bool, error)
GetMap(keys ...string) (map[string]JSONObject, error)
GetArray(keys ...string) ([]JSONObject, error)
GetTime(keys ...string) (time.Time, error)
GetString(keys ...string) (string, error)
Unmarshal(obj interface{}, keys ...string) error
Equals(obj JSONObject) bool
unmarshalValue(val reflect.Value) error
// IsZero() bool
Interface() interface{}
isCompond() bool
}
type JSONValue struct {
}
var (
JSONNull = &JSONValue{}
JSONTrue = &JSONBool{data: true}
JSONFalse = &JSONBool{data: false}
)
type JSONDict struct {
JSONValue
data sortedmap.SSortedMap
}
type JSONArray struct {
JSONValue
data []JSONObject
}
type JSONString struct {
JSONValue
data string
}
type JSONInt struct {
JSONValue
data int64
}
type JSONFloat struct {
JSONValue
data float64
}
type JSONBool struct {
JSONValue
data bool
}
func skipEmpty(str []byte, offset int) int {
i := offset
for i < len(str) {
switch str[i] {
case ' ', '\t', '\n', '\r':
i++
default:
return i
}
}
return i
}
func hexchar2num(v byte) (byte, error) {
switch {
case v >= '0' && v <= '9':
return v - '0', nil
case v >= 'a' && v <= 'f':
return v - 'a' + 10, nil
case v >= 'A' && v <= 'F':
return v - 'A' + 10, nil
default:
return 0, ErrInvalidChar // fmt.Errorf("Illegal char %c", v)
}
}
func hexstr2byte(str []byte) (byte, error) {
if len(str) < 2 {
return 0, ErrInvalidHex // fmt.Errorf("Input must be 2 hex chars")
}
v1, e := hexchar2num(str[0])
if e != nil {
return 0, e
}
v2, e := hexchar2num(str[1])
if e != nil {
return 0, e
}
return v1*16 + v2, nil
}
func hexstr2rune(str []byte) (rune, error) {
if len(str) < 4 {
return 0, ErrInvalidRune // fmt.Errorf("Input must be 4 hex chars")
}
v1, e := hexstr2byte(str[0:2])
if e != nil {
return 0, e
}
v2, e := hexstr2byte(str[2:4])
if e != nil {
return 0, e
}
return rune(v1)*256 + rune(v2), nil
}
func parseQuoteString(str []byte, offset int, quotec byte) (string, int, error) {
var (
buffer []byte
runebytes = make([]byte, 4)
runen int
i = offset
)
ret:
for i < len(str) {
switch str[i] {
case '\\':
if i+1 < len(str) {
i++
switch str[i] {
case 'u':
i++
if i+4 >= len(str) {
return "", i, NewJSONError(str, i, "Incomplete unicode")
}
r, e := hexstr2rune(str[i : i+4])
if e != nil {
return "", i, NewJSONError(str, i, e.Error())
}
runen = utf8.EncodeRune(runebytes, r)
buffer = append(buffer, runebytes[0:runen]...)
i += 4
case 'x':
i++
if i+2 >= len(str) {
return "", i, NewJSONError(str, i, "Incomplete hex")
}
b, e := hexstr2byte(str[i : i+2])
if e != nil {
return "", i, NewJSONError(str, i, e.Error())
}
buffer = append(buffer, b)
i += 2
case 'n':
buffer = append(buffer, '\n')
i++
case 'r':
buffer = append(buffer, '\r')
i++
case 't':
buffer = append(buffer, '\t')
i++
default:
buffer = append(buffer, str[i])
i++
}
} else {
return "", i, NewJSONError(str, i, "Incomplete escape")
}
case quotec:
i++
break ret
default:
buffer = append(buffer, str[i])
i++
}
}
return string(buffer), i, nil
}
func parseString(str []byte, offset int) (string, bool, int, error) {
var (
i = offset
)
if c := str[i]; c == '"' || c == '\'' {
r, newOfs, err := parseQuoteString(str, i+1, c)
return r, true, newOfs, err
}
ret2:
for i < len(str) {
switch str[i] {
case ' ', ':', ',', '\t', '\n', '}', ']':
break ret2
default:
i++
}
}
return string(str[offset:i]), false, i, nil
}
func parseJSONValue(str []byte, offset int) (JSONObject, int, error) {
val, quote, i, e := parseString(str, offset)
if e != nil {
return nil, i, errors.Wrap(e, "parseString")
} else if quote {
return &JSONString{data: val}, i, nil
} else {
lval := strings.ToLower(val)
if len(lval) == 0 || lval == "null" || lval == "none" {
return JSONNull, i, nil
}
if lval == "true" || lval == "yes" {
return JSONTrue, i, nil
}
if lval == "false" || lval == "no" {
return JSONFalse, i, nil
}
ival, err := strconv.ParseInt(val, 10, 64)
if err == nil {
return &JSONInt{data: ival}, i, nil
}
fval, err := strconv.ParseFloat(val, 64)
if err == nil {
return &JSONFloat{data: fval}, i, nil
}
return &JSONString{data: val}, i, nil
}
}
func quoteString(str string) string {
sb := &strings.Builder{}
sb.Grow(len(str) + 2)
sb.WriteByte('"')
for i := 0; i < len(str); i++ {
switch c := str[i]; c {
case '"':
sb.Write([]byte{'\\', '"'})
case '\r':
sb.Write([]byte{'\\', 'r'})
case '\n':
sb.Write([]byte{'\\', 'n'})
case '\t':
sb.Write([]byte{'\\', 't'})
case '\\':
sb.Write([]byte{'\\', '\\'})
default:
sb.WriteByte(c)
}
}
sb.WriteByte('"')
return sb.String()
}
func jsonPrettyString(o JSONObject, level int) string {
var buffer bytes.Buffer
for i := 0; i < level; i++ {
buffer.WriteString(" ")
}
buffer.WriteString(o.String())
return buffer.String()
}
func (this *JSONString) PrettyString() string {
return this.String()
}
func (this *JSONString) prettyString(level int) string {
return jsonPrettyString(this, level)
}
func (this *JSONValue) parse(str []byte, offset int) (int, error) {
return 0, nil
}
func (this *JSONValue) PrettyString() string {
return this.String()
}
func (this *JSONValue) prettyString(level int) string {
return jsonPrettyString(this, level)
}
func (this *JSONInt) PrettyString() string {
return this.String()
}
func (this *JSONInt) prettyString(level int) string {
return jsonPrettyString(this, level)
}
func (this *JSONFloat) PrettyString() string {
return this.String()
}
func (this *JSONFloat) prettyString(level int) string {
return jsonPrettyString(this, level)
}
func (this *JSONBool) PrettyString() string {
return this.String()
}
func (this *JSONBool) prettyString(level int) string {
return jsonPrettyString(this, level)
}
func parseDict(str []byte, offset int) (sortedmap.SSortedMap, int, error) {
smap := sortedmap.NewSortedMap()
if str[offset] != '{' {
return smap, offset, NewJSONError(str, offset, "{ not found")
}
var i = offset + 1
var e error = nil
var key string
var stop = false
for !stop && i < len(str) {
i = skipEmpty(str, i)
if i >= len(str) {
return smap, i, NewJSONError(str, i, "Truncated")
}
if str[i] == '}' {
stop = true
i++
continue
}
key, _, i, e = parseString(str, i)
if e != nil {
return smap, i, errors.Wrap(e, "parseString")
}
if i >= len(str) {
return smap, i, NewJSONError(str, i, "Truncated")
}
i = skipEmpty(str, i)
if i >= len(str) {
return smap, i, NewJSONError(str, i, "Truncated")
}
if str[i] != ':' {
return smap, i, NewJSONError(str, i, ": not found")
}
i++
i = skipEmpty(str, i)
if i >= len(str) {
return smap, i, NewJSONError(str, i, "Truncated")
}
var val JSONObject = nil
switch str[i] {
case '[':
val = &JSONArray{}
i, e = val.parse(str, i)
case '{':
val = &JSONDict{}
i, e = val.parse(str, i)
default:
val, i, e = parseJSONValue(str, i)
}
if e != nil {
return smap, i, errors.Wrap(e, "parse misc")
}
smap = sortedmap.Add(smap, key, val)
i = skipEmpty(str, i)
if i >= len(str) {
return smap, i, NewJSONError(str, i, "Truncated")
}
switch str[i] {
case ',':
i++
case '}':
i++
stop = true
default:
return smap, i, NewJSONError(str, i, "Unexpected char")
}
}
return smap, i, nil
}
func parseArray(str []byte, offset int) ([]JSONObject, int, error) {
if str[offset] != '[' {
return nil, offset, NewJSONError(str, offset, "[ not found")
}
var (
list []JSONObject
i = offset + 1
val JSONObject
e error
stop bool
)
for !stop && i < len(str) {
i = skipEmpty(str, i)
if i >= len(str) {
return list, i, NewJSONError(str, i, "Truncated")
}
switch str[i] {
case ']':
i++
stop = true
continue
case '[':
val = &JSONArray{}
i, e = val.parse(str, i)
case '{':
val = &JSONDict{}
i, e = val.parse(str, i)
default:
val, i, e = parseJSONValue(str, i)
}
if e != nil {
return list, i, errors.Wrap(e, "parse misc")
}
if i >= len(str) {
return list, i, NewJSONError(str, i, "Truncated")
}
list = append(list, val)
i = skipEmpty(str, i)
if i >= len(str) {
return list, i, NewJSONError(str, i, "Truncated")
}
switch str[i] {
case ',':
i++
case ']':
i++
stop = true
default:
return list, i, NewJSONError(str, i, "Unexpected char")
}
}
return list, i, nil
}
func (this *JSONDict) parse(str []byte, offset int) (int, error) {
smap, i, e := parseDict(str, offset)
if e == nil {
this.data = smap
return i, nil
}
return i, errors.Wrap(e, "parseDict")
}
func (this *JSONDict) SortedKeys() []string {
return this.data.Keys()
}
func (this *JSONDict) PrettyString() string {
return this.prettyString(0)
}
func (this *JSONDict) prettyString(level int) string {
var buffer bytes.Buffer
var linebuf bytes.Buffer
for i := 0; i < level; i++ {
linebuf.WriteString(" ")
}
var tab = linebuf.String()
buffer.WriteString(tab)
buffer.WriteByte('{')
var idx = 0
for iter := sortedmap.NewIterator(this.data); iter.HasMore(); iter.Next() {
k, vInf := iter.Get()
v := vInf.(JSONObject)
if idx > 0 {
buffer.WriteString(",")
}
buffer.WriteByte('\n')
buffer.WriteString(tab)
buffer.WriteString(" ")
buffer.WriteByte('"')
buffer.WriteString(k)
buffer.WriteString("\":")
_, okdict := v.(*JSONDict)
_, okarray := v.(*JSONArray)
if okdict || okarray {
buffer.WriteByte('\n')
buffer.WriteString(v.prettyString(level + 2))
} else {
buffer.WriteByte(' ')
buffer.WriteString(v.String())
}
idx++
}
if len(this.data) > 0 {
buffer.WriteByte('\n')
buffer.WriteString(tab)
}
buffer.WriteByte('}')
return buffer.String()
}
func (this *JSONArray) parse(str []byte, offset int) (int, error) {
val, i, e := parseArray(str, offset)
if e == nil {
this.data = val
}
return i, errors.Wrap(e, "parseArray")
}
func (this *JSONArray) PrettyString() string {
return this.prettyString(0)
}
func (this *JSONArray) prettyString(level int) string {
var buffer bytes.Buffer
var linebuf bytes.Buffer
for i := 0; i < level; i++ {
linebuf.WriteString(" ")
}
var tab = linebuf.String()
buffer.WriteString(tab)
buffer.WriteByte('[')
for idx, v := range this.data {
if idx > 0 {
buffer.WriteString(",")
}
buffer.WriteByte('\n')
buffer.WriteString(v.prettyString(level + 1))
}
if len(this.data) > 0 {
buffer.WriteByte('\n')
buffer.WriteString(tab)
}
buffer.WriteByte(']')
return buffer.String()
}
func ParseString(str string) (JSONObject, error) {
return Parse([]byte(str))
}
func Parse(str []byte) (JSONObject, error) {
var i = 0
i = skipEmpty(str, i)
var val JSONObject = nil
var e error = nil
if i < len(str) {
switch str[i] {
case '{':
val = &JSONDict{}
i, e = val.parse(str, i)
case '[':
val = &JSONArray{}
i, e = val.parse(str, i)
default:
val, i, e = parseJSONValue(str, i)
// return nil, NewJSONError(str, i, "Invalid JSON string")
}
if e != nil {
return nil, errors.Wrap(e, "parse misc")
} else {
return val, nil
}
} else {
return nil, NewJSONError(str, i, "Empty string")
}
}