Parse parses the json and returns a result. This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.
(json string)
| 469 | // If you are consuming JSON from an unpredictable source then you may want to |
| 470 | // use the Valid function first. |
| 471 | func Parse(json string) Result { |
| 472 | var value Result |
| 473 | i := 0 |
| 474 | for ; i < len(json); i++ { |
| 475 | if json[i] == '{' || json[i] == '[' { |
| 476 | value.Type = JSON |
| 477 | value.Raw = json[i:] // just take the entire raw |
| 478 | break |
| 479 | } |
| 480 | if json[i] <= ' ' { |
| 481 | continue |
| 482 | } |
| 483 | switch json[i] { |
| 484 | case '+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', |
| 485 | 'i', 'I', 'N': |
| 486 | value.Type = Number |
| 487 | value.Raw, value.Num = tonum(json[i:]) |
| 488 | case 'n': |
| 489 | if i+1 < len(json) && json[i+1] != 'u' { |
| 490 | // nan |
| 491 | value.Type = Number |
| 492 | value.Raw, value.Num = tonum(json[i:]) |
| 493 | } else { |
| 494 | // null |
| 495 | value.Type = Null |
| 496 | value.Raw = tolit(json[i:]) |
| 497 | } |
| 498 | case 't': |
| 499 | value.Type = True |
| 500 | value.Raw = tolit(json[i:]) |
| 501 | case 'f': |
| 502 | value.Type = False |
| 503 | value.Raw = tolit(json[i:]) |
| 504 | case '"': |
| 505 | value.Type = String |
| 506 | value.Raw, value.Str = tostr(json[i:]) |
| 507 | default: |
| 508 | return Result{} |
| 509 | } |
| 510 | break |
| 511 | } |
| 512 | if value.Exists() { |
| 513 | value.Index = i |
| 514 | } |
| 515 | return value |
| 516 | } |
| 517 | |
| 518 | // ParseBytes parses the json and returns a result. |
| 519 | // If working with bytes, this method preferred over Parse(string(data)) |
searching dependent graphs…