-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathjsonhelper.go
616 lines (569 loc) · 12.3 KB
/
jsonhelper.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
package gou
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"net/url"
"strconv"
"strings"
"unicode/utf8"
)
// Convert a slice of bytes into an array by ensuring it is wrapped
// with []
func MakeJsonList(b []byte) []byte {
if !bytes.HasPrefix(b, []byte{'['}) {
b = append([]byte{'['}, b...)
b = append(b, ']')
}
return b
}
func JsonString(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return `""`
}
return string(b)
}
func firstNonWsRune(by []byte) (r rune, ok bool) {
for {
if len(by) == 0 {
return 0, false
}
r, numBytes := utf8.DecodeRune(by)
switch r {
case '\t', '\n', '\r', ' ':
by = by[numBytes:] // advance past the current whitespace rune and continue
continue
case utf8.RuneError: // This is returned when invalid UTF8 is found
return 0, false
}
return r, true
}
}
// Determines if the bytes is a json array, only looks at prefix
// not parsing the entire thing
func IsJson(by []byte) bool {
firstRune, ok := firstNonWsRune(by)
if !ok {
return false
}
if firstRune == '[' || firstRune == '{' {
return true
}
return false
}
// Determines if the bytes is a json array, only looks at prefix
// not parsing the entire thing
func IsJsonArray(by []byte) bool {
firstRune, ok := firstNonWsRune(by)
if !ok {
return false
}
if firstRune == '[' {
return true
}
return false
}
func IsJsonObject(by []byte) bool {
firstRune, ok := firstNonWsRune(by)
if !ok {
return false
}
if firstRune == '{' {
return true
}
return false
}
type JsonRawWriter struct {
bytes.Buffer
}
func (m *JsonRawWriter) MarshalJSON() ([]byte, error) {
return m.Bytes(), nil
}
func (m *JsonRawWriter) Raw() json.RawMessage {
return json.RawMessage(m.Bytes())
}
// A wrapper around a map[string]interface{} to facilitate coercion
// of json data to what you want
//
// allows usage such as this
//
// jh := NewJsonHelper([]byte(`{
// "name":"string",
// "ints":[1,5,9,11],
// "int":1,
// "int64":1234567890,
// "MaxSize" : 1048576,
// "strings":["string1"],
// "nested":{
// "nest":"string2",
// "strings":["string1"],
// "int":2,
// "list":["value"],
// "nest2":{
// "test":"good"
// }
// },
// "nested2":[
// {"sub":5}
// ]
// }`)
//
// i := jh.Int("nested.int") // 2
// i2 := jh.Int("ints[1]") // 5 array position 1 from [1,5,9,11]
// s := jh.String("nested.nest") // "string2"
//
type JsonHelper map[string]interface{}
func NewJsonHelper(b []byte) JsonHelper {
jh := make(JsonHelper)
json.Unmarshal(b, &jh)
return jh
}
func NewJsonHelperReader(r io.Reader) (jh JsonHelper, err error) {
jh = make(JsonHelper)
err = json.NewDecoder(r).Decode(&jh)
return
}
func NewJsonHelpers(b []byte) []JsonHelper {
var jhl []JsonHelper
json.Unmarshal(MakeJsonList(b), &jhl)
return jhl
}
func NewJsonHelperMapString(m map[string]string) JsonHelper {
jh := make(JsonHelper)
for k, v := range m {
jh[k] = v
}
return jh
}
// Make a JsonHelper from http response. This will automatically
// close the response body
func NewJsonHelperFromResp(resp *http.Response) (JsonHelper, error) {
jh := make(JsonHelper)
if resp == nil || resp.Body == nil {
return jh, fmt.Errorf("No response or response body to read")
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(respBytes) == 0 {
return jh, fmt.Errorf("No data in response")
}
if err := json.Unmarshal(respBytes, &jh); err != nil {
return jh, err
}
return jh, nil
}
func jsonList(v interface{}) []interface{} {
switch v.(type) {
case []interface{}:
return v.([]interface{})
}
return nil
}
func jsonEntry(name string, v interface{}) (interface{}, bool) {
switch val := v.(type) {
case map[string]interface{}:
if root, ok := val[name]; ok {
return root, true
} else {
return nil, false
}
case JsonHelper:
return val.Get(name), true
case []interface{}:
return v, true
default:
Debug("no type? ", name, " ", v)
return nil, false
}
}
// Get the key (or keypath) value as interface, mostly used
// internally through String, etc methods
//
// jh.Get("name.subname")
// jh.Get("name/subname")
// jh.Get("name.arrayname[1]")
// jh.Get("name.arrayname[]")
func (j JsonHelper) Get(n string) interface{} {
if len(j) == 0 {
return nil
}
var parts []string
if strings.Contains(n, "/") {
parts = strings.Split(n, "/")
if strings.HasPrefix(n, "/") && len(parts) > 0 {
parts = parts[1:]
}
} else {
parts = strings.Split(n, ".")
}
var root interface{}
var err error
var ok, isList, listEntry bool
var ln, st, idx int
for ict, name := range parts {
isList = strings.HasSuffix(name, "[]")
listEntry = strings.HasSuffix(name, "]") && !isList
ln, idx = len(name), -1
if isList || listEntry {
st = strings.Index(name, "[")
idx, err = strconv.Atoi(name[st+1 : ln-1])
name = name[:st]
}
if ict == 0 {
root, ok = j[name]
} else {
root, ok = jsonEntry(name, root)
}
if !ok {
if len(parts) > 0 {
// lets ensure the actual json-value doesn't have period in key
root, ok = j[n]
if !ok {
return nil
} else {
return root
}
} else {
return nil
}
}
if isList {
return jsonList(root)
} else if listEntry && err == nil {
if lst := jsonList(root); lst != nil && len(lst) > idx {
root = lst[idx]
} else {
return nil
}
}
}
return root
}
// Get a Helper from a string path
func (j JsonHelper) Helper(n string) JsonHelper {
v := j.Get(n)
if v == nil {
return nil
}
switch vt := v.(type) {
case map[string]interface{}:
cn := JsonHelper{}
for n, val := range vt {
cn[n] = val
}
return cn
case map[string]string:
cn := JsonHelper{}
for n, val := range vt {
cn[n] = val
}
return cn
case JsonHelper:
return vt
default:
//Infof("wrong type: %T", v)
}
return nil
}
// Get list of Helpers at given name. Trys to coerce into
// proper Helper type
func (j JsonHelper) Helpers(n string) []JsonHelper {
v := j.Get(n)
if v == nil {
return nil
}
switch val := v.(type) {
case []map[string]interface{}:
hl := make([]JsonHelper, 0)
for _, mapVal := range val {
hl = append(hl, mapVal)
}
return hl
case []interface{}:
jhl := make([]JsonHelper, 0)
for _, item := range val {
if jh, ok := item.(map[string]interface{}); ok {
jhl = append(jhl, jh)
}
}
return jhl
}
return nil
}
// Gets slice of interface{}
func (j JsonHelper) List(n string) []interface{} {
v := j.Get(n)
switch val := v.(type) {
case []string:
il := make([]interface{}, len(val))
for i, val := range val {
il[i] = val
}
return il
case []interface{}:
return val
}
return nil
}
func (j JsonHelper) String(n string) string {
if v := j.Get(n); v != nil {
val, _ := CoerceString(v)
return val
}
return ""
}
func (j JsonHelper) Strings(n string) []string {
if v := j.Get(n); v != nil {
return CoerceStrings(v)
}
return nil
}
func (j JsonHelper) Ints(n string) []int {
v := j.Get(n)
if v == nil {
return nil
}
return CoerceInts(v)
}
func (j JsonHelper) StringSafe(n string) (string, bool) {
v := j.Get(n)
if v != nil {
if s, ok := v.(string); ok {
return s, ok
}
}
return "", false
}
func (j JsonHelper) Int(n string) int {
i, ok := j.IntSafe(n)
if !ok {
return -1
}
return i
}
func (j JsonHelper) IntSafe(n string) (int, bool) {
v := j.Get(n)
return valToInt(v)
}
func (j JsonHelper) Int64(n string) int64 {
i64, ok := j.Int64Safe(n)
if !ok {
return -1
}
return i64
}
func (j JsonHelper) Int64Safe(n string) (int64, bool) {
v := j.Get(n)
return valToInt64(v)
}
func (j JsonHelper) Float64(n string) float64 {
v := j.Get(n)
f64, err := CoerceFloat(v)
if err != nil {
return math.NaN()
}
return f64
}
func (j JsonHelper) Float64Safe(n string) (float64, bool) {
v := j.Get(n)
if v == nil {
return math.NaN(), true
}
fv, err := CoerceFloat(v)
if err != nil {
return math.NaN(), false
}
return fv, true
}
func (j JsonHelper) Uint64(n string) uint64 {
v := j.Get(n)
if v != nil {
return CoerceUintShort(v)
}
return 0
}
func (j JsonHelper) Uint64Safe(n string) (uint64, bool) {
v := j.Get(n)
if v != nil {
if uv, err := CoerceUint(v); err == nil {
return uv, true
}
}
return 0, false
}
func (j JsonHelper) BoolSafe(n string) (val bool, ok bool) {
v := j.Get(n)
if v != nil {
switch v.(type) {
case bool:
return v.(bool), true
case string:
if s := v.(string); len(s) > 0 {
if b, err := strconv.ParseBool(s); err == nil {
return b, true
}
}
}
}
return false, false
}
func (j JsonHelper) Bool(n string) bool {
val, ok := j.BoolSafe(n)
if !ok {
return false
}
return val
}
func (j JsonHelper) Map(n string) map[string]interface{} {
v := j.Get(n)
if v == nil {
return nil
}
m, ok := v.(map[string]interface{})
if !ok {
return nil
}
return m
}
func (j JsonHelper) MapSafe(n string) (map[string]interface{}, bool) {
v := j.Get(n)
if v == nil {
return nil, false
}
m, ok := v.(map[string]interface{})
if !ok {
return nil, false
}
return m, true
}
func (j JsonHelper) PrettyJson() []byte {
jsonPretty, _ := json.MarshalIndent(j, " ", " ")
return jsonPretty
}
func (j JsonHelper) Keys() []string {
keys := make([]string, 0)
for key := range j {
keys = append(keys, key)
}
return keys
}
func (j JsonHelper) HasKey(name string) bool {
if val := j.Get(name); val != nil {
return true
}
return false
}
// GobDecode overwrites the receiver, which must be a pointer,
// with the value represented by the byte slice, which was written
// by GobEncode, usually for the same concrete type.
// GobDecode([]byte) error
func (j *JsonHelper) GobDecode(data []byte) error {
var mv map[string]interface{}
if err := json.Unmarshal(data, &mv); err != nil {
return err
}
*j = JsonHelper(mv)
return nil
}
func (j *JsonHelper) GobEncode() ([]byte, error) {
by, err := json.Marshal(j)
return by, err
}
// The following consts are from http://code.google.com/p/go-bit/ (Apache licensed). It
// lets us figure out how wide go ints are, and determine their max and min values.
// Note the use of << to create an untyped constant.
const bitsPerWord = 32 << uint(^uint(0)>>63)
// Implementation-specific size of int and uint in bits.
const BitsPerWord = bitsPerWord // either 32 or 64
// Implementation-specific integer limit values.
const (
MaxInt = 1<<(BitsPerWord-1) - 1 // either 1<<31 - 1 or 1<<63 - 1
MinInt = -MaxInt - 1 // either -1 << 31 or -1 << 63
MaxUint = 1<<BitsPerWord - 1 // either 1<<32 - 1 or 1<<64 - 1
)
func flattenHelper(uv url.Values, jh JsonHelper, pre string) error {
for k, v := range jh {
if err := flattenJsonValue(uv, v, pre+k); err != nil {
return err
}
}
return nil
}
func flattenJsonMap(uv url.Values, jsonMap map[string]interface{}, pre string) error {
for k, v := range jsonMap {
if err := flattenJsonValue(uv, v, pre+k); err != nil {
return err
}
}
return nil
}
func flattenJsonValue(uv url.Values, v interface{}, k string) error {
// TODO: all these ints aren't possible are they?
switch x := v.(type) {
case []string:
uv[k] = x
// case []interface{}:
// sva := make([]string, 0)
// for _, av := range x {
// if err := flattenJsonValue(n, av, k); err != nil {
// return nil
// }
// }
// if len(sva) > 0 {
// uv[k] = sva
// }
case map[string]bool:
// what to do?
Info("not implemented: [string]bool")
case map[string]interface{}:
if len(x) > 0 {
if err := flattenJsonMap(uv, x, k+"."); err != nil {
return err
}
}
case string:
uv.Set(k, x)
case bool:
if x == true {
uv.Set(k, "t")
} else {
uv.Set(k, "f")
}
case int:
uv.Set(k, strconv.FormatInt(int64(x), 10))
case int8:
uv.Set(k, strconv.FormatInt(int64(x), 10))
case int16:
uv.Set(k, strconv.FormatInt(int64(x), 10))
case int32:
uv.Set(k, strconv.FormatInt(int64(x), 10))
case int64:
uv.Set(k, strconv.FormatInt(x, 10))
case uint:
uv.Set(k, strconv.FormatUint(uint64(x), 10))
case uint8:
uv.Set(k, strconv.FormatUint(uint64(x), 10))
case uint16:
uv.Set(k, strconv.FormatUint(uint64(x), 10))
case uint32:
uv.Set(k, strconv.FormatUint(uint64(x), 10))
case uint64:
uv.Set(k, strconv.FormatUint(x, 10))
case float32:
uv.Set(k, strconv.FormatFloat(float64(x), 'f', -1, 64))
case float64:
uv.Set(k, strconv.FormatFloat(x, 'f', -1, 64))
default:
// what types don't we support?
// []interface{}
}
return nil
}