forked from bitly/go-simplejson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplejson.go
505 lines (434 loc) · 11.6 KB
/
simplejson.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
package simplejson
import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
)
var (
ErrNoMap = errors.New("type assertion to map[string]interface{} failed")
ErrNoArray = errors.New("type assertion to []interface{} failed")
ErrNoBool = errors.New("type assertion to bool failed")
ErrNoString = errors.New("type assertion to string failed")
ErrNoFloat = errors.New("type assertion to float64 failed")
ErrNoByteArray = errors.New("type assertion to []byte failed")
)
// returns the current implementation version
func Version() string {
return "0.4.3-gobs"
}
type Json struct {
data interface{}
}
// Cast to Json{}
func AsJson(obj interface{}) *Json {
return &Json{obj}
}
// Load loads JSON from `reader` io.Reader and return a new `Json` object
func Load(reader io.Reader) (*Json, error) {
j := new(Json)
dec := json.NewDecoder(reader)
err := dec.Decode(&j.data)
if err != nil {
return nil, err
} else {
return j, nil
}
}
// LoadBytes load JSON from `body` []byte and return a new `Json` object
func LoadBytes(body []byte) (*Json, error) {
j := new(Json)
err := j.UnmarshalJSON(body)
if err != nil {
return nil, err
}
return j, nil
}
// LoadString loads JSON from `body` string and return a new `Json` object
func LoadString(body string) (*Json, error) {
return LoadBytes([]byte(body))
}
// LoadPartial load JSON from `body` []byte and return a new `Json` object.
// It also returns any remaining bytes from the input.
func LoadPartial(body []byte) (*Json, []byte, error) {
j := new(Json)
b := bytes.NewReader(body)
dec := json.NewDecoder(b)
err := dec.Decode(&j.data)
n := (dec.Buffered().(*bytes.Reader)).Len() + b.Len()
rest := body[len(body)-n:]
if err != nil {
return nil, rest, err
}
return j, rest, nil
}
// LoadPartialString load JSON from `body` string and return a new `Json` object.
// It also returns any remaining bytes from the input.
func LoadPartialString(body string) (*Json, string, error) {
j, rest, err := LoadPartial([]byte(body))
return j, string(rest), err
}
// DumpOption is the type of DumpBytes/DumpString options
type DumpOption func(enc *json.Encoder)
// EscapeHTML instruct DumpBytes/DumpString to escape HTML in JSON valus (if true)
func EscapeHTML(escape bool) DumpOption {
return func(enc *json.Encoder) {
enc.SetEscapeHTML(escape)
}
}
// Indent sets the indentation level (passed as string of spaces) for DumpBytes/DumpString
func Indent(s string) DumpOption {
return func(enc *json.Encoder) {
enc.SetIndent("", s)
}
}
// DumpBytes convert Go data object to JSON []byte
func DumpBytes(obj interface{}, options ...DumpOption) ([]byte, error) {
// turns out json.Marsh HTMLEncodes string values to please some browsers
// result, err := json.Marshal(obj)
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)
for _, opt := range options {
opt(enc)
}
err := enc.Encode(obj)
return b.Bytes(), err
}
// DumpString encode Go data object to JSON string
func DumpString(obj interface{}, options ...DumpOption) (string, error) {
if result, err := DumpBytes(obj, options...); err != nil {
return "", err
} else {
return string(result), nil
}
}
// MustDumpBytes encode Go data object to JSON []byte (panic in case of error)
func MustDumpBytes(obj interface{}, options ...DumpOption) []byte {
if res, err := DumpBytes(obj, options...); err != nil {
panic(err)
} else {
return res
}
}
// MustDumpString encode Go data object to JSON string (panic in case of error)
func MustDumpString(obj interface{}, options ...DumpOption) string {
if res, err := DumpString(obj, options...); err != nil {
panic(err)
} else {
return res
}
}
// Encode returns its marshaled data as `[]byte`
func (j *Json) Encode() ([]byte, error) {
return j.MarshalJSON()
}
// Implements the json.Unmarshaler interface.
func (j *Json) UnmarshalJSON(p []byte) error {
return json.Unmarshal(p, &j.data)
}
// Implements the json.Marshaler interface.
func (j *Json) MarshalJSON() ([]byte, error) {
return DumpBytes(&j.data)
}
// Set modifies `Json` map by `key` and `value`
// Useful for changing single key/value in a `Json` object easily.
func (j *Json) Set(key string, val interface{}) {
m, err := j.Map()
if err != nil {
return
}
m[key] = val
}
// Nil returns true if this json object is nil
func (j *Json) Nil() bool {
return j == nil || j.data == nil
}
// Get returns a pointer to a new `Json` object
// for `key` in its `map` representation
//
// useful for chaining operations (to traverse a nested JSON):
// js.Get("top_level").Get("dict").Get("value").Int()
func (j *Json) Get(key string) *Json {
m, err := j.Map()
if err == nil {
if val, ok := m[key]; ok {
return &Json{val}
}
}
return &Json{nil}
}
// GetPath searches for the item as specified by the branch
// without the need to deep dive using Get()'s.
//
// js.GetPath("top_level", "dict")
func (j *Json) GetPath(branch ...string) *Json {
jin := j
for i := range branch {
m, err := jin.Map()
if err != nil {
return &Json{nil}
}
if val, ok := m[branch[i]]; ok {
jin = &Json{val}
} else {
return &Json{nil}
}
}
return jin
}
// GetIndex resturns a pointer to a new `Json` object
// for `index` in its `array` representation
//
// this is the analog to Get when accessing elements of
// a json array instead of a json object:
// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int()
func (j *Json) GetIndex(index int) *Json {
a, err := j.Array()
if err == nil {
if len(a) > index {
return &Json{a[index]}
}
}
return &Json{nil}
}
// CheckGet returns a pointer to a new `Json` object and
// a `bool` identifying success or failure
//
// useful for chained operations when success is important:
// if data, ok := js.Get("top_level").CheckGet("inner"); ok {
// log.Println(data)
// }
func (j *Json) CheckGet(key string) (*Json, bool) {
m, err := j.Map()
if err == nil {
if val, ok := m[key]; ok {
return &Json{val}, true
}
}
return nil, false
}
// Return value as interface{}
func (j *Json) Data() interface{} {
return j.data
}
// Map type asserts to `map`
func (j *Json) Map() (map[string]interface{}, error) {
if m, ok := (j.data).(map[string]interface{}); ok {
return m, nil
}
return nil, ErrNoMap
}
// Array type asserts to an `array`
func (j *Json) Array() ([]interface{}, error) {
if a, ok := (j.data).([]interface{}); ok {
return a, nil
}
return nil, ErrNoArray
}
// MakeArray always return an `array`
// (this is useful for HAL responses that can return either an array or a single element ):
func (j *Json) MakeArray() []interface{} {
if a, ok := (j.data).([]interface{}); ok {
return a
} else {
return []interface{}{j.data}
}
}
// Bool type asserts to `bool`
func (j *Json) Bool() (bool, error) {
if s, ok := (j.data).(bool); ok {
return s, nil
}
return false, ErrNoBool
}
// String type asserts to `string`
func (j *Json) String() (string, error) {
if s, ok := (j.data).(string); ok {
return s, nil
}
return "", ErrNoString
}
// Float64 type asserts to `float64`
func (j *Json) Float64() (float64, error) {
if i, ok := (j.data).(float64); ok {
return i, nil
}
return -1, ErrNoFloat
}
// Int type asserts to `float64` then converts to `int`
func (j *Json) Int() (int, error) {
if f, ok := (j.data).(float64); ok {
return int(f), nil
}
return -1, ErrNoFloat
}
// Int type asserts to `float64` then converts to `int64`
func (j *Json) Int64() (int64, error) {
if f, ok := (j.data).(float64); ok {
return int64(f), nil
}
return -1, ErrNoFloat
}
// Bytes type asserts to `[]byte`
func (j *Json) Bytes() ([]byte, error) {
if s, ok := (j.data).(string); ok {
return []byte(s), nil
}
return nil, ErrNoByteArray
}
// StringArray type asserts to an `array` of `string`
func (j *Json) StringArray() ([]string, error) {
arr, err := j.Array()
if err != nil {
return nil, err
}
retArr := make([]string, 0, len(arr))
for _, a := range arr {
s, ok := a.(string)
if !ok {
return nil, err
}
retArr = append(retArr, s)
}
return retArr, nil
}
// MustArray guarantees the return of a `[]interface{}` (with optional default)
//
// useful when you want to interate over array values in a succinct manner:
// for i, v := range js.Get("results").MustArray() {
// fmt.Println(i, v)
// }
func (j *Json) MustArray(args ...[]interface{}) []interface{} {
var def []interface{}
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustArray() received too many arguments %d", len(args))
}
a, err := j.Array()
if err == nil {
return a
}
return def
}
// MustMap guarantees the return of a `map[string]interface{}` (with optional default)
//
// useful when you want to interate over map values in a succinct manner:
// for k, v := range js.Get("dictionary").MustMap() {
// fmt.Println(k, v)
// }
func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} {
var def map[string]interface{}
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustMap() received too many arguments %d", len(args))
}
a, err := j.Map()
if err == nil {
return a
}
return def
}
// MustString guarantees the return of a `string` (with optional default)
//
// useful when you explicitly want a `string` in a single value return context:
// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default"))
func (j *Json) MustString(args ...string) string {
var def string
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustString() received too many arguments %d", len(args))
}
s, err := j.String()
if err == nil {
return s
}
return def
}
// MustInt guarantees the return of an `int` (with optional default)
//
// useful when you explicitly want an `int` in a single value return context:
// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150))
func (j *Json) MustInt(args ...int) int {
var def int
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustInt() received too many arguments %d", len(args))
}
i, err := j.Int()
if err == nil {
return i
}
return def
}
// MustInt64 guarantees the return of an `int64` (with optional default)
//
// useful when you explicitly want an `int64` in a single value return context:
// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150))
func (j *Json) MustInt64(args ...int64) int64 {
var def int64
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustInt64() received too many arguments %d", len(args))
}
i, err := j.Int64()
if err == nil {
return i
}
return def
}
// MustFloat64 guarantees the return of a `float64` (with optional default)
//
// useful when you explicitly want a `float64` in a single value return context:
// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150))
func (j *Json) MustFloat64(args ...float64) float64 {
var def float64
switch len(args) {
case 0:
break
case 1:
def = args[0]
default:
log.Panicf("MustFloat64() received too many arguments %d", len(args))
}
i, err := j.Float64()
if err == nil {
return i
}
return def
}
//
// basic type for quick conversion to JSON
//
type Bag map[string]interface{}
// this is an alias for json.RawMessage, for clients that don't include encoding/json
type Raw = json.RawMessage
// this is an alias for json.Marshal, for clients that don't include encoding/json
func Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
// this is an alias for json.Unmarshal, for clients that don't include encoding/json
func Unmarshal(data []byte, v interface{}) error {
return json.Unmarshal(data, v)
}