jsonhelper.go 12.3 KB
Newer Older
Aaron Raddon's avatar
Aaron Raddon committed
1 2 3
package gou

import (
4
	"bytes"
Aaron Raddon's avatar
Aaron Raddon committed
5
	"encoding/json"
6
	"fmt"
7
	"io"
8
	"io/ioutil"
Aaron Raddon's avatar
Aaron Raddon committed
9
	"math"
10
	"net/http"
Aaron Raddon's avatar
Aaron Raddon committed
11
	"net/url"
Aaron Raddon's avatar
Aaron Raddon committed
12 13
	"strconv"
	"strings"
Aaron Raddon's avatar
Aaron Raddon committed
14
	"unicode/utf8"
Aaron Raddon's avatar
Aaron Raddon committed
15 16
)

Aaron Raddon's avatar
Aaron Raddon committed
17 18 19
// Convert a slice of bytes into an array by ensuring it is wrapped
//  with []
func MakeJsonList(b []byte) []byte {
20 21 22 23 24 25 26
	if !bytes.HasPrefix(b, []byte{'['}) {
		b = append([]byte{'['}, b...)
		b = append(b, ']')
	}
	return b
}

Aaron Raddon's avatar
Aaron Raddon committed
27
func JsonString(v interface{}) string {
Aaron Raddon's avatar
Aaron Raddon committed
28 29 30 31
	b, err := json.Marshal(v)
	if err != nil {
		return `""`
	}
Aaron Raddon's avatar
Aaron Raddon committed
32 33 34
	return string(b)
}

Aaron Raddon's avatar
Aaron Raddon committed
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
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
}

89 90 91 92 93 94 95 96 97 98 99 100
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())
}

101
// A wrapper around a map[string]interface{} to facilitate coercion
Aaron Raddon's avatar
Aaron Raddon committed
102
// of json data to what you want
103
//
Aaron Raddon's avatar
Aaron Raddon committed
104
// allows usage such as this
105
//
Aaron Raddon's avatar
Aaron Raddon committed
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
//		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"
//
Aaron Raddon's avatar
Aaron Raddon committed
131 132
type JsonHelper map[string]interface{}

Aaron Raddon's avatar
Aaron Raddon committed
133 134 135 136 137
func NewJsonHelper(b []byte) JsonHelper {
	jh := make(JsonHelper)
	json.Unmarshal(b, &jh)
	return jh
}
Aaron Raddon's avatar
Aaron Raddon committed
138

139 140 141 142 143
func NewJsonHelperReader(r io.Reader) (jh JsonHelper, err error) {
	jh = make(JsonHelper)
	err = json.NewDecoder(r).Decode(&jh)
	return
}
Aaron Raddon's avatar
Aaron Raddon committed
144

145 146
func NewJsonHelpers(b []byte) []JsonHelper {
	var jhl []JsonHelper
Aaron Raddon's avatar
Aaron Raddon committed
147
	json.Unmarshal(MakeJsonList(b), &jhl)
148 149
	return jhl
}
Aaron Raddon's avatar
Aaron Raddon committed
150

Aaron Raddon's avatar
Aaron Raddon committed
151 152 153 154 155 156 157 158
func NewJsonHelperMapString(m map[string]string) JsonHelper {
	jh := make(JsonHelper)
	for k, v := range m {
		jh[k] = v
	}
	return jh
}

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
// 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
}

Aaron Raddon's avatar
Aaron Raddon committed
180 181 182 183 184 185 186
func jsonList(v interface{}) []interface{} {
	switch v.(type) {
	case []interface{}:
		return v.([]interface{})
	}
	return nil
}
Aaron Raddon's avatar
Aaron Raddon committed
187

Aaron Raddon's avatar
Aaron Raddon committed
188
func jsonEntry(name string, v interface{}) (interface{}, bool) {
189
	switch val := v.(type) {
Aaron Raddon's avatar
Aaron Raddon committed
190
	case map[string]interface{}:
191
		if root, ok := val[name]; ok {
Aaron Raddon's avatar
Aaron Raddon committed
192 193 194 195
			return root, true
		} else {
			return nil, false
		}
196
	case JsonHelper:
197
		return val.Get(name), true
Aaron Raddon's avatar
Aaron Raddon committed
198 199 200 201 202 203 204
	case []interface{}:
		return v, true
	default:
		Debug("no type? ", name, " ", v)
		return nil, false
	}
}
Aaron Raddon's avatar
Aaron Raddon committed
205 206 207 208 209

// Get the key (or keypath) value as interface, mostly used
// internally through String, etc methods
//
//    jh.Get("name.subname")
210 211 212
//    jh.Get("name/subname")
//    jh.Get("name.arrayname[1]")
//    jh.Get("name.arrayname[]")
Aaron Raddon's avatar
Aaron Raddon committed
213
func (j JsonHelper) Get(n string) interface{} {
214 215 216
	if len(j) == 0 {
		return nil
	}
217 218 219 220 221 222 223 224 225
	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, ".")
	}
Aaron Raddon's avatar
Aaron Raddon committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	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 {
245 246 247 248 249
			if len(parts) > 0 {
				// lets ensure the actual json-value doesn't have period in key
				root, ok = j[n]
				if !ok {
					return nil
250 251
				} else {
					return root
252 253 254 255 256
				}
			} else {
				return nil
			}

Aaron Raddon's avatar
Aaron Raddon committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270
		}
		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
}
271

Aaron Raddon's avatar
Aaron Raddon committed
272 273
// Get a Helper from a string path
func (j JsonHelper) Helper(n string) JsonHelper {
Aaron Raddon's avatar
Aaron Raddon committed
274 275 276 277 278 279 280 281 282
	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
Aaron Raddon's avatar
Aaron Raddon committed
283
		}
Aaron Raddon's avatar
Aaron Raddon committed
284 285 286 287 288 289 290 291 292 293 294
		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)
Aaron Raddon's avatar
Aaron Raddon committed
295 296 297 298 299 300
	}
	return nil
}

// Get list of Helpers at given name.  Trys to coerce into
// proper Helper type
301 302 303 304 305
func (j JsonHelper) Helpers(n string) []JsonHelper {
	v := j.Get(n)
	if v == nil {
		return nil
	}
Aaron Raddon's avatar
Aaron Raddon committed
306
	switch val := v.(type) {
307 308
	case []map[string]interface{}:
		hl := make([]JsonHelper, 0)
Aaron Raddon's avatar
Aaron Raddon committed
309 310
		for _, mapVal := range val {
			hl = append(hl, mapVal)
311 312 313
		}
		return hl
	case []interface{}:
Aaron Raddon's avatar
Aaron Raddon committed
314 315 316 317
		jhl := make([]JsonHelper, 0)
		for _, item := range val {
			if jh, ok := item.(map[string]interface{}); ok {
				jhl = append(jhl, jh)
318 319
			}
		}
Aaron Raddon's avatar
Aaron Raddon committed
320
		return jhl
321 322 323 324
	}

	return nil
}
Aaron Raddon's avatar
Aaron Raddon committed
325 326

// Gets slice of interface{}
Aaron Raddon's avatar
Aaron Raddon committed
327 328
func (j JsonHelper) List(n string) []interface{} {
	v := j.Get(n)
Aaron Raddon's avatar
Aaron Raddon committed
329 330 331 332 333 334 335 336 337
	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
Aaron Raddon's avatar
Aaron Raddon committed
338 339 340
	}
	return nil
}
Aaron Raddon's avatar
Aaron Raddon committed
341

Aaron Raddon's avatar
Aaron Raddon committed
342
func (j JsonHelper) String(n string) string {
Aaron Raddon's avatar
Aaron Raddon committed
343
	if v := j.Get(n); v != nil {
344 345
		val, _ := CoerceString(v)
		return val
Aaron Raddon's avatar
Aaron Raddon committed
346 347 348
	}
	return ""
}
Aaron Raddon's avatar
Aaron Raddon committed
349 350
func (j JsonHelper) Strings(n string) []string {
	if v := j.Get(n); v != nil {
Aaron Raddon's avatar
Aaron Raddon committed
351
		return CoerceStrings(v)
Aaron Raddon's avatar
Aaron Raddon committed
352 353 354
	}
	return nil
}
355
func (j JsonHelper) Ints(n string) []int {
356 357 358 359
	v := j.Get(n)
	if v == nil {
		return nil
	}
Aaron Raddon's avatar
Aaron Raddon committed
360
	return CoerceInts(v)
361
}
Aaron Raddon's avatar
Aaron Raddon committed
362 363 364 365 366 367 368 369 370
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
}
Aaron Raddon's avatar
Aaron Raddon committed
371

Aaron Raddon's avatar
Aaron Raddon committed
372
func (j JsonHelper) Int(n string) int {
373 374 375 376 377 378
	i, ok := j.IntSafe(n)
	if !ok {
		return -1
	}
	return i
}
Aaron Raddon's avatar
Aaron Raddon committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392

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
}

393
func (j JsonHelper) Int64Safe(n string) (int64, bool) {
Aaron Raddon's avatar
Aaron Raddon committed
394
	v := j.Get(n)
395
	return valToInt64(v)
396
}
Aaron Raddon's avatar
Aaron Raddon committed
397

Aaron Raddon's avatar
Aaron Raddon committed
398
func (j JsonHelper) Float64(n string) float64 {
399
	v := j.Get(n)
400 401 402 403
	f64, err := CoerceFloat(v)
	if err != nil {
		return math.NaN()
	}
Aaron Raddon's avatar
Aaron Raddon committed
404 405 406 407 408 409
	return f64
}

func (j JsonHelper) Float64Safe(n string) (float64, bool) {
	v := j.Get(n)
	if v == nil {
410
		return math.NaN(), true
Aaron Raddon's avatar
Aaron Raddon committed
411 412 413 414 415 416
	}
	fv, err := CoerceFloat(v)
	if err != nil {
		return math.NaN(), false
	}
	return fv, true
417 418
}

Aaron Raddon's avatar
Aaron Raddon committed
419 420 421
func (j JsonHelper) Uint64(n string) uint64 {
	v := j.Get(n)
	if v != nil {
422
		return CoerceUintShort(v)
Aaron Raddon's avatar
Aaron Raddon committed
423 424 425
	}
	return 0
}
426

Aaron Raddon's avatar
Aaron Raddon committed
427 428 429 430 431 432 433 434 435 436
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
}

437
func (j JsonHelper) BoolSafe(n string) (val bool, ok bool) {
Aaron Raddon's avatar
Aaron Raddon committed
438 439 440 441
	v := j.Get(n)
	if v != nil {
		switch v.(type) {
		case bool:
442
			return v.(bool), true
Aaron Raddon's avatar
Aaron Raddon committed
443 444 445
		case string:
			if s := v.(string); len(s) > 0 {
				if b, err := strconv.ParseBool(s); err == nil {
446
					return b, true
Aaron Raddon's avatar
Aaron Raddon committed
447 448 449 450
				}
			}
		}
	}
451 452 453 454 455 456 457 458 459 460
	return false, false
}

func (j JsonHelper) Bool(n string) bool {
	val, ok := j.BoolSafe(n)
	if !ok {
		return false
	}

	return val
Aaron Raddon's avatar
Aaron Raddon committed
461
}
462

463 464 465 466 467 468 469 470 471 472 473 474
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
}

Dave Revell's avatar
Dave Revell committed
475 476 477 478 479 480 481 482 483 484 485 486
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
}

Aaron Raddon's avatar
Aaron Raddon committed
487 488 489 490
func (j JsonHelper) PrettyJson() []byte {
	jsonPretty, _ := json.MarshalIndent(j, "  ", "  ")
	return jsonPretty
}
Aaron Raddon's avatar
Aaron Raddon committed
491 492
func (j JsonHelper) Keys() []string {
	keys := make([]string, 0)
Shawn Smith's avatar
Shawn Smith committed
493
	for key := range j {
Aaron Raddon's avatar
Aaron Raddon committed
494 495 496 497
		keys = append(keys, key)
	}
	return keys
}
498 499 500 501 502 503
func (j JsonHelper) HasKey(name string) bool {
	if val := j.Get(name); val != nil {
		return true
	}
	return false
}
Aaron Raddon's avatar
Aaron Raddon committed
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
// 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
}

522
// The following consts are from http://code.google.com/p/go-bit/ (Apache licensed). It
523 524 525 526 527 528 529 530 531 532 533 534 535 536
// 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
)
Aaron Raddon's avatar
Aaron Raddon committed
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

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
}