Best Got code snippet using got.JSON
gjson_test.go
Source:gjson_test.go
...97 testEscapePath(t, json, "test.key\\.v", "val6")98 testEscapePath(t, json, "test.keyk\\*.key\\?", "val7")99}100// this json block is poorly formed on purpose.101var basicJSON = `{"age":100, "name":{"here":"B\\\"R"},102 "noop":{"what is a wren?":"a bird"},103 "happy":true,"immortal":false,104 "items":[1,2,3,{"tags":[1,2,3],"points":[[1,2],[3,4]]},4,5,6,7],105 "arr":["1",2,"3",{"hello":"world"},"4",5],106 "vals":[1,2,3,{"sadf":sdf"asdf"}],"name":{"first":"tom","last":null},107 "created":"2014-05-16T08:28:06.989Z",108 "loggy":{109 "programmers": [110 {111 "firstName": "Brett",112 "lastName": "McLaughlin",113 "email": "aaaa",114 "tag": "good"115 },116 {117 "firstName": "Jason",118 "lastName": "Hunter",119 "email": "bbbb",120 "tag": "bad"121 },122 {123 "firstName": "Elliotte",124 "lastName": "Harold",125 "email": "cccc",126 "tag":, "good"127 },128 {129 "firstName": 1002.3,130 "age": 101131 }132 ]133 },134 "lastly":{"yay":"final"}135}`136var basicJSONB = []byte(basicJSON)137func TestTimeResult(t *testing.T) {138 assert(t, Get(basicJSON, "created").String() ==139 Get(basicJSON, "created").Time().Format(time.RFC3339Nano))140}141func TestParseAny(t *testing.T) {142 assert(t, Parse("100").Float() == 100)143 assert(t, Parse("true").Bool())144 assert(t, Parse("false").Bool() == false)145 assert(t, Parse("yikes").Exists() == false)146}147func TestManyVariousPathCounts(t *testing.T) {148 json := `{"a":"a","b":"b","c":"c"}`149 counts := []int{3, 4, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127,150 128, 129, 255, 256, 257, 511, 512, 513}151 paths := []string{"a", "b", "c"}152 expects := []string{"a", "b", "c"}153 for _, count := range counts {154 var gpaths []string155 var gexpects []string156 for i := 0; i < count; i++ {157 if i < len(paths) {158 gpaths = append(gpaths, paths[i])159 gexpects = append(gexpects, expects[i])160 } else {161 gpaths = append(gpaths, fmt.Sprintf("not%d", i))162 gexpects = append(gexpects, "null")163 }164 }165 results := GetMany(json, gpaths...)166 for i := 0; i < len(paths); i++ {167 if results[i].String() != expects[i] {168 t.Fatalf("expected '%v', got '%v'", expects[i],169 results[i].String())170 }171 }172 }173}174func TestManyRecursion(t *testing.T) {175 var json string176 var path string177 for i := 0; i < 100; i++ {178 json += `{"a":`179 path += ".a"180 }181 json += `"b"`182 for i := 0; i < 100; i++ {183 json += `}`184 }185 path = path[1:]186 assert(t, GetMany(json, path)[0].String() == "b")187}188func TestByteSafety(t *testing.T) {189 jsonb := []byte(`{"name":"Janet","age":38}`)190 mtok := GetBytes(jsonb, "name")191 if mtok.String() != "Janet" {192 t.Fatalf("expected %v, got %v", "Jason", mtok.String())193 }194 mtok2 := GetBytes(jsonb, "age")195 if mtok2.Raw != "38" {196 t.Fatalf("expected %v, got %v", "Jason", mtok2.Raw)197 }198 jsonb[9] = 'T'199 jsonb[12] = 'd'200 jsonb[13] = 'y'201 if mtok.String() != "Janet" {202 t.Fatalf("expected %v, got %v", "Jason", mtok.String())203 }204}205func get(json, path string) Result {206 return GetBytes([]byte(json), path)207}208func TestBasic(t *testing.T) {209 var mtok Result210 mtok = get(basicJSON, `loggy.programmers.#[tag="good"].firstName`)211 if mtok.String() != "Brett" {212 t.Fatalf("expected %v, got %v", "Brett", mtok.String())213 }214 mtok = get(basicJSON, `loggy.programmers.#[tag="good"]#.firstName`)215 if mtok.String() != `["Brett","Elliotte"]` {216 t.Fatalf("expected %v, got %v", `["Brett","Elliotte"]`, mtok.String())217 }218}219func TestIsArrayIsObject(t *testing.T) {220 mtok := get(basicJSON, "loggy")221 assert(t, mtok.IsObject())222 assert(t, !mtok.IsArray())223 mtok = get(basicJSON, "loggy.programmers")224 assert(t, !mtok.IsObject())225 assert(t, mtok.IsArray())226 mtok = get(basicJSON, `loggy.programmers.#[tag="good"]#.firstName`)227 assert(t, mtok.IsArray())228 mtok = get(basicJSON, `loggy.programmers.0.firstName`)229 assert(t, !mtok.IsObject())230 assert(t, !mtok.IsArray())231}232func TestPlus53BitInts(t *testing.T) {233 json := `{"IdentityData":{"GameInstanceId":634866135153775564}}`234 value := Get(json, "IdentityData.GameInstanceId")235 assert(t, value.Uint() == 634866135153775564)236 assert(t, value.Int() == 634866135153775564)237 assert(t, value.Float() == 634866135153775616)238 json = `{"IdentityData":{"GameInstanceId":634866135153775564.88172}}`239 value = Get(json, "IdentityData.GameInstanceId")240 assert(t, value.Uint() == 634866135153775616)241 assert(t, value.Int() == 634866135153775616)242 assert(t, value.Float() == 634866135153775616.88172)243 json = `{244 "min_uint64": 0,245 "max_uint64": 18446744073709551615,246 "overflow_uint64": 18446744073709551616,247 "min_int64": -9223372036854775808,248 "max_int64": 9223372036854775807,249 "overflow_int64": 9223372036854775808,250 "min_uint53": 0,251 "max_uint53": 4503599627370495,252 "overflow_uint53": 4503599627370496,253 "min_int53": -2251799813685248,254 "max_int53": 2251799813685247,255 "overflow_int53": 2251799813685248256 }`257 assert(t, Get(json, "min_uint53").Uint() == 0)258 assert(t, Get(json, "max_uint53").Uint() == 4503599627370495)259 assert(t, Get(json, "overflow_uint53").Int() == 4503599627370496)260 assert(t, Get(json, "min_int53").Int() == -2251799813685248)261 assert(t, Get(json, "max_int53").Int() == 2251799813685247)262 assert(t, Get(json, "overflow_int53").Int() == 2251799813685248)263 assert(t, Get(json, "min_uint64").Uint() == 0)264 assert(t, Get(json, "max_uint64").Uint() == 18446744073709551615)265 // this next value overflows the max uint64 by one which will just266 // flip the number to zero267 assert(t, Get(json, "overflow_uint64").Int() == 0)268 assert(t, Get(json, "min_int64").Int() == -9223372036854775808)269 assert(t, Get(json, "max_int64").Int() == 9223372036854775807)270 // this next value overflows the max int64 by one which will just271 // flip the number to the negative sign.272 assert(t, Get(json, "overflow_int64").Int() == -9223372036854775808)273}274func TestIssue38(t *testing.T) {275 // These should not fail, even though the unicode is invalid.276 Get(`["S3O PEDRO DO BUTI\udf93"]`, "0")277 Get(`["S3O PEDRO DO BUTI\udf93asdf"]`, "0")278 Get(`["S3O PEDRO DO BUTI\udf93\u"]`, "0")279 Get(`["S3O PEDRO DO BUTI\udf93\u1"]`, "0")280 Get(`["S3O PEDRO DO BUTI\udf93\u13"]`, "0")281 Get(`["S3O PEDRO DO BUTI\udf93\u134"]`, "0")282 Get(`["S3O PEDRO DO BUTI\udf93\u1345"]`, "0")283 Get(`["S3O PEDRO DO BUTI\udf93\u1345asd"]`, "0")284}285func TestTypes(t *testing.T) {286 assert(t, (Result{Type: String}).Type.String() == "String")287 assert(t, (Result{Type: Number}).Type.String() == "Number")288 assert(t, (Result{Type: Null}).Type.String() == "Null")289 assert(t, (Result{Type: False}).Type.String() == "False")290 assert(t, (Result{Type: True}).Type.String() == "True")291 assert(t, (Result{Type: JSON}).Type.String() == "JSON")292 assert(t, (Result{Type: 100}).Type.String() == "")293 // bool294 assert(t, (Result{Type: String, Str: "true"}).Bool())295 assert(t, (Result{Type: True}).Bool())296 assert(t, (Result{Type: False}).Bool() == false)297 assert(t, (Result{Type: Number, Num: 1}).Bool())298 // int299 assert(t, (Result{Type: String, Str: "1"}).Int() == 1)300 assert(t, (Result{Type: True}).Int() == 1)301 assert(t, (Result{Type: False}).Int() == 0)302 assert(t, (Result{Type: Number, Num: 1}).Int() == 1)303 // uint304 assert(t, (Result{Type: String, Str: "1"}).Uint() == 1)305 assert(t, (Result{Type: True}).Uint() == 1)306 assert(t, (Result{Type: False}).Uint() == 0)307 assert(t, (Result{Type: Number, Num: 1}).Uint() == 1)308 // float309 assert(t, (Result{Type: String, Str: "1"}).Float() == 1)310 assert(t, (Result{Type: True}).Float() == 1)311 assert(t, (Result{Type: False}).Float() == 0)312 assert(t, (Result{Type: Number, Num: 1}).Float() == 1)313}314func TestForEach(t *testing.T) {315 Result{}.ForEach(nil)316 Result{Type: String, Str: "Hello"}.ForEach(func(_, value Result) bool {317 assert(t, value.String() == "Hello")318 return false319 })320 Result{Type: JSON, Raw: "*invalid*"}.ForEach(nil)321 json := ` {"name": {"first": "Janet","last": "Prichard"},322 "asd\nf":"\ud83d\udd13","age": 47}`323 var count int324 ParseBytes([]byte(json)).ForEach(func(key, value Result) bool {325 count++326 return true327 })328 assert(t, count == 3)329 ParseBytes([]byte(`{"bad`)).ForEach(nil)330 ParseBytes([]byte(`{"ok":"bad`)).ForEach(nil)331}332func TestMap(t *testing.T) {333 assert(t, len(ParseBytes([]byte(`"asdf"`)).Map()) == 0)334 assert(t, ParseBytes([]byte(`{"asdf":"ghjk"`)).Map()["asdf"].String() ==335 "ghjk")336 assert(t, len(Result{Type: JSON, Raw: "**invalid**"}.Map()) == 0)337 assert(t, Result{Type: JSON, Raw: "**invalid**"}.Value() == nil)338 assert(t, Result{Type: JSON, Raw: "{"}.Map() != nil)339}340func TestBasic1(t *testing.T) {341 mtok := get(basicJSON, `loggy.programmers`)342 var count int343 mtok.ForEach(func(key, value Result) bool {344 if key.Exists() {345 t.Fatalf("expected %v, got %v", false, key.Exists())346 }347 count++348 if count == 3 {349 return false350 }351 if count == 1 {352 i := 0353 value.ForEach(func(key, value Result) bool {354 switch i {355 case 0:356 if key.String() != "firstName" ||357 value.String() != "Brett" {358 t.Fatalf("expected %v/%v got %v/%v", "firstName",359 "Brett", key.String(), value.String())360 }361 case 1:362 if key.String() != "lastName" ||363 value.String() != "McLaughlin" {364 t.Fatalf("expected %v/%v got %v/%v", "lastName",365 "McLaughlin", key.String(), value.String())366 }367 case 2:368 if key.String() != "email" || value.String() != "aaaa" {369 t.Fatalf("expected %v/%v got %v/%v", "email", "aaaa",370 key.String(), value.String())371 }372 }373 i++374 return true375 })376 }377 return true378 })379 if count != 3 {380 t.Fatalf("expected %v, got %v", 3, count)381 }382}383func TestBasic2(t *testing.T) {384 mtok := get(basicJSON, `loggy.programmers.#[age=101].firstName`)385 if mtok.String() != "1002.3" {386 t.Fatalf("expected %v, got %v", "1002.3", mtok.String())387 }388 mtok = get(basicJSON,389 `loggy.programmers.#[firstName != "Brett"].firstName`)390 if mtok.String() != "Jason" {391 t.Fatalf("expected %v, got %v", "Jason", mtok.String())392 }393 mtok = get(basicJSON, `loggy.programmers.#[firstName % "Bre*"].email`)394 if mtok.String() != "aaaa" {395 t.Fatalf("expected %v, got %v", "aaaa", mtok.String())396 }397 mtok = get(basicJSON, `loggy.programmers.#[firstName !% "Bre*"].email`)398 if mtok.String() != "bbbb" {399 t.Fatalf("expected %v, got %v", "bbbb", mtok.String())400 }401 mtok = get(basicJSON, `loggy.programmers.#[firstName == "Brett"].email`)402 if mtok.String() != "aaaa" {403 t.Fatalf("expected %v, got %v", "aaaa", mtok.String())404 }405 mtok = get(basicJSON, "loggy")406 if mtok.Type != JSON {407 t.Fatalf("expected %v, got %v", JSON, mtok.Type)408 }409 if len(mtok.Map()) != 1 {410 t.Fatalf("expected %v, got %v", 1, len(mtok.Map()))411 }412 programmers := mtok.Map()["programmers"]413 if programmers.Array()[1].Map()["firstName"].Str != "Jason" {414 t.Fatalf("expected %v, got %v", "Jason",415 mtok.Map()["programmers"].Array()[1].Map()["firstName"].Str)416 }417}418func TestBasic3(t *testing.T) {419 var mtok Result420 if Parse(basicJSON).Get("loggy.programmers").Get("1").421 Get("firstName").Str != "Jason" {422 t.Fatalf("expected %v, got %v", "Jason", Parse(basicJSON).423 Get("loggy.programmers").Get("1").Get("firstName").Str)424 }425 var token Result426 if token = Parse("-102"); token.Num != -102 {427 t.Fatalf("expected %v, got %v", -102, token.Num)428 }429 if token = Parse("102"); token.Num != 102 {430 t.Fatalf("expected %v, got %v", 102, token.Num)431 }432 if token = Parse("102.2"); token.Num != 102.2 {433 t.Fatalf("expected %v, got %v", 102.2, token.Num)434 }435 if token = Parse(`"hello"`); token.Str != "hello" {436 t.Fatalf("expected %v, got %v", "hello", token.Str)437 }438 if token = Parse(`"\"he\nllo\""`); token.Str != "\"he\nllo\"" {439 t.Fatalf("expected %v, got %v", "\"he\nllo\"", token.Str)440 }441 mtok = get(basicJSON, "loggy.programmers.#.firstName")442 if len(mtok.Array()) != 4 {443 t.Fatalf("expected 4, got %v", len(mtok.Array()))444 }445 for i, ex := range []string{"Brett", "Jason", "Elliotte", "1002.3"} {446 if mtok.Array()[i].String() != ex {447 t.Fatalf("expected '%v', got '%v'", ex, mtok.Array()[i].String())448 }449 }450 mtok = get(basicJSON, "loggy.programmers.#.asd")451 if mtok.Type != JSON {452 t.Fatalf("expected %v, got %v", JSON, mtok.Type)453 }454 if len(mtok.Array()) != 0 {455 t.Fatalf("expected 0, got %v", len(mtok.Array()))456 }457}458func TestBasic4(t *testing.T) {459 if get(basicJSON, "items.3.tags.#").Num != 3 {460 t.Fatalf("expected 3, got %v", get(basicJSON, "items.3.tags.#").Num)461 }462 if get(basicJSON, "items.3.points.1.#").Num != 2 {463 t.Fatalf("expected 2, got %v",464 get(basicJSON, "items.3.points.1.#").Num)465 }466 if get(basicJSON, "items.#").Num != 8 {467 t.Fatalf("expected 6, got %v", get(basicJSON, "items.#").Num)468 }469 if get(basicJSON, "vals.#").Num != 4 {470 t.Fatalf("expected 4, got %v", get(basicJSON, "vals.#").Num)471 }472 if !get(basicJSON, "name.last").Exists() {473 t.Fatal("expected true, got false")474 }475 token := get(basicJSON, "name.here")476 if token.String() != "B\\\"R" {477 t.Fatal("expecting 'B\\\"R'", "got", token.String())478 }479 token = get(basicJSON, "arr.#")480 if token.String() != "6" {481 fmt.Printf("%#v\n", token)482 t.Fatal("expecting 6", "got", token.String())483 }484 token = get(basicJSON, "arr.3.hello")485 if token.String() != "world" {486 t.Fatal("expecting 'world'", "got", token.String())487 }488 _ = token.Value().(string)489 token = get(basicJSON, "name.first")490 if token.String() != "tom" {491 t.Fatal("expecting 'tom'", "got", token.String())492 }493 _ = token.Value().(string)494 token = get(basicJSON, "name.last")495 if token.String() != "" {496 t.Fatal("expecting ''", "got", token.String())497 }498 if token.Value() != nil {499 t.Fatal("should be nil")500 }501}502func TestBasic5(t *testing.T) {503 token := get(basicJSON, "age")504 if token.String() != "100" {505 t.Fatal("expecting '100'", "got", token.String())506 }507 _ = token.Value().(float64)508 token = get(basicJSON, "happy")509 if token.String() != "true" {510 t.Fatal("expecting 'true'", "got", token.String())511 }512 _ = token.Value().(bool)513 token = get(basicJSON, "immortal")514 if token.String() != "false" {515 t.Fatal("expecting 'false'", "got", token.String())516 }517 _ = token.Value().(bool)518 token = get(basicJSON, "noop")519 if token.String() != `{"what is a wren?":"a bird"}` {520 t.Fatal("expecting '"+`{"what is a wren?":"a bird"}`+"'", "got",521 token.String())522 }523 _ = token.Value().(map[string]interface{})524 if get(basicJSON, "").Value() != nil {525 t.Fatal("should be nil")526 }527 get(basicJSON, "vals.hello")528 type msi = map[string]interface{}529 type fi = []interface{}530 mm := Parse(basicJSON).Value().(msi)531 fn := mm["loggy"].(msi)["programmers"].(fi)[1].(msi)["firstName"].(string)532 if fn != "Jason" {533 t.Fatalf("expecting %v, got %v", "Jason", fn)534 }535}536func TestUnicode(t *testing.T) {537 var json = `{"key":0,"çæ
åµä¸è§£":{"key":1,"çæ
åµ":2}}`538 if Get(json, "çæ
åµä¸è§£.key").Num != 1 {539 t.Fatal("fail")540 }541 if Get(json, "çæ
åµä¸è§£.çæ
åµ").Num != 2 {542 t.Fatal("fail")543 }544 if Get(json, "çæ
åµä¸è§£.ç?åµ").Num != 2 {545 t.Fatal("fail")546 }547 if Get(json, "çæ
åµä¸è§£.ç?*").Num != 2 {548 t.Fatal("fail")549 }550 if Get(json, "çæ
åµä¸è§£.*?åµ").Num != 2 {551 t.Fatal("fail")552 }553 if Get(json, "çæ
?ä¸è§£.*?åµ").Num != 2 {554 t.Fatal("fail")555 }556 if Get(json, "çæ
ä¸è§£.*?åµ").Num != 0 {557 t.Fatal("fail")558 }559}560func TestUnescape(t *testing.T) {561 unescape(string([]byte{'\\', '\\', 0}))562 unescape(string([]byte{'\\', '/', '\\', 'b', '\\', 'f'}))563}564func assert(t testing.TB, cond bool) {565 if !cond {566 panic("assert failed")567 }568}569func TestLess(t *testing.T) {570 assert(t, !Result{Type: Null}.Less(Result{Type: Null}, true))571 assert(t, Result{Type: Null}.Less(Result{Type: False}, true))572 assert(t, Result{Type: Null}.Less(Result{Type: True}, true))573 assert(t, Result{Type: Null}.Less(Result{Type: JSON}, true))574 assert(t, Result{Type: Null}.Less(Result{Type: Number}, true))575 assert(t, Result{Type: Null}.Less(Result{Type: String}, true))576 assert(t, !Result{Type: False}.Less(Result{Type: Null}, true))577 assert(t, Result{Type: False}.Less(Result{Type: True}, true))578 assert(t, Result{Type: String, Str: "abc"}.Less(Result{Type: String,579 Str: "bcd"}, true))580 assert(t, Result{Type: String, Str: "ABC"}.Less(Result{Type: String,581 Str: "abc"}, true))582 assert(t, !Result{Type: String, Str: "ABC"}.Less(Result{Type: String,583 Str: "abc"}, false))584 assert(t, Result{Type: Number, Num: 123}.Less(Result{Type: Number,585 Num: 456}, true))586 assert(t, !Result{Type: Number, Num: 456}.Less(Result{Type: Number,587 Num: 123}, true))588 assert(t, !Result{Type: Number, Num: 456}.Less(Result{Type: Number,589 Num: 456}, true))590 assert(t, stringLessInsensitive("abcde", "BBCDE"))591 assert(t, stringLessInsensitive("abcde", "bBCDE"))592 assert(t, stringLessInsensitive("Abcde", "BBCDE"))593 assert(t, stringLessInsensitive("Abcde", "bBCDE"))594 assert(t, !stringLessInsensitive("bbcde", "aBCDE"))595 assert(t, !stringLessInsensitive("bbcde", "ABCDE"))596 assert(t, !stringLessInsensitive("Bbcde", "aBCDE"))597 assert(t, !stringLessInsensitive("Bbcde", "ABCDE"))598 assert(t, !stringLessInsensitive("abcde", "ABCDE"))599 assert(t, !stringLessInsensitive("Abcde", "ABCDE"))600 assert(t, !stringLessInsensitive("abcde", "ABCDE"))601 assert(t, !stringLessInsensitive("ABCDE", "ABCDE"))602 assert(t, !stringLessInsensitive("abcde", "abcde"))603 assert(t, !stringLessInsensitive("123abcde", "123Abcde"))604 assert(t, !stringLessInsensitive("123Abcde", "123Abcde"))605 assert(t, !stringLessInsensitive("123Abcde", "123abcde"))606 assert(t, !stringLessInsensitive("123abcde", "123abcde"))607 assert(t, !stringLessInsensitive("124abcde", "123abcde"))608 assert(t, !stringLessInsensitive("124Abcde", "123Abcde"))609 assert(t, !stringLessInsensitive("124Abcde", "123abcde"))610 assert(t, !stringLessInsensitive("124abcde", "123abcde"))611 assert(t, stringLessInsensitive("124abcde", "125abcde"))612 assert(t, stringLessInsensitive("124Abcde", "125Abcde"))613 assert(t, stringLessInsensitive("124Abcde", "125abcde"))614 assert(t, stringLessInsensitive("124abcde", "125abcde"))615}616func TestIssue6(t *testing.T) {617 data := `{618 "code": 0,619 "msg": "",620 "data": {621 "sz002024": {622 "qfqday": [623 [624 "2014-01-02",625 "8.93",626 "9.03",627 "9.17",628 "8.88",629 "621143.00"630 ],631 [632 "2014-01-03",633 "9.03",634 "9.30",635 "9.47",636 "8.98",637 "1624438.00"638 ]639 ]640 }641 }642 }`643 var num []string644 for _, v := range Get(data, "data.sz002024.qfqday.0").Array() {645 num = append(num, v.String())646 }647 if fmt.Sprintf("%v", num) != "[2014-01-02 8.93 9.03 9.17 8.88 621143.00]" {648 t.Fatalf("invalid result")649 }650}651var exampleJSON = `{652 "widget": {653 "debug": "on",654 "window": {655 "title": "Sample Konfabulator Widget",656 "name": "main_window",657 "width": 500,658 "height": 500659 },660 "image": {661 "src": "Images/Sun.png",662 "hOffset": 250,663 "vOffset": 250,664 "alignment": "center"665 },666 "text": {667 "data": "Click Here",668 "size": 36,669 "style": "bold",670 "vOffset": 100,671 "alignment": "center",672 "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"673 }674 }675}`676func TestNewParse(t *testing.T) {677 //fmt.Printf("%v\n", parse2(exampleJSON, "widget").String())678}679func TestUnmarshalMap(t *testing.T) {680 var m1 = Parse(exampleJSON).Value().(map[string]interface{})681 var m2 map[string]interface{}682 if err := json.Unmarshal([]byte(exampleJSON), &m2); err != nil {683 t.Fatal(err)684 }685 b1, err := json.Marshal(m1)686 if err != nil {687 t.Fatal(err)688 }689 b2, err := json.Marshal(m2)690 if err != nil {691 t.Fatal(err)692 }693 if bytes.Compare(b1, b2) != 0 {694 t.Fatal("b1 != b2")695 }696}697func TestSingleArrayValue(t *testing.T) {698 var json = `{"key": "value","key2":[1,2,3,4,"A"]}`699 var result = Get(json, "key")700 var array = result.Array()701 if len(array) != 1 {702 t.Fatal("array is empty")703 }704 if array[0].String() != "value" {705 t.Fatalf("got %s, should be %s", array[0].String(), "value")706 }707 array = Get(json, "key2.#").Array()708 if len(array) != 1 {709 t.Fatalf("got '%v', expected '%v'", len(array), 1)710 }711 array = Get(json, "key3").Array()712 if len(array) != 0 {713 t.Fatalf("got '%v', expected '%v'", len(array), 0)714 }715}716var manyJSON = ` {717 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{718 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{719 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{720 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{721 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{722 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{723 "a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"a":{"hello":"world"724 }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}725 "position":{"type":"Point","coordinates":[-115.24,33.09]},726 "loves":["world peace"],727 "name":{"last":"Anderson","first":"Nancy"},728 "age":31729 "":{"a":"emptya","b":"emptyb"},730 "name.last":"Yellow",731 "name.first":"Cat",732}`733func combine(results []Result) string {734 return fmt.Sprintf("%v", results)735}736func TestManyBasic(t *testing.T) {737 testWatchForFallback = true738 defer func() {739 testWatchForFallback = false740 }()741 testMany := func(shouldFallback bool, expect string, paths ...string) {742 results := GetManyBytes(743 []byte(manyJSON),744 paths...,745 )746 if len(results) != len(paths) {747 t.Fatalf("expected %v, got %v", len(paths), len(results))748 }749 if fmt.Sprintf("%v", results) != expect {750 fmt.Printf("%v\n", paths)751 t.Fatalf("expected %v, got %v", expect, results)752 }753 //if testLastWasFallback != shouldFallback {754 // t.Fatalf("expected %v, got %v", shouldFallback, testLastWasFallback)755 //}756 }757 testMany(false, "[Point]", "position.type")758 testMany(false, `[emptya ["world peace"] 31]`, ".a", "loves", "age")759 testMany(false, `[["world peace"]]`, "loves")760 testMany(false, `[{"last":"Anderson","first":"Nancy"} Nancy]`, "name",761 "name.first")762 testMany(true, `[]`, strings.Repeat("a.", 40)+"hello")763 res := Get(manyJSON, strings.Repeat("a.", 48)+"a")764 testMany(true, `[`+res.String()+`]`, strings.Repeat("a.", 48)+"a")765 // these should fallback766 testMany(true, `[Cat Nancy]`, "name\\.first", "name.first")767 testMany(true, `[world]`, strings.Repeat("a.", 70)+"hello")768}769func testMany(t *testing.T, json string, paths, expected []string) {770 testManyAny(t, json, paths, expected, true)771 testManyAny(t, json, paths, expected, false)772}773func testManyAny(t *testing.T, json string, paths, expected []string,774 bytes bool) {775 var result []Result776 for i := 0; i < 2; i++ {777 var which string778 if i == 0 {779 which = "Get"780 result = nil781 for j := 0; j < len(expected); j++ {782 if bytes {783 result = append(result, GetBytes([]byte(json), paths[j]))784 } else {785 result = append(result, Get(json, paths[j]))786 }787 }788 } else if i == 1 {789 which = "GetMany"790 if bytes {791 result = GetManyBytes([]byte(json), paths...)792 } else {793 result = GetMany(json, paths...)794 }795 }796 for j := 0; j < len(expected); j++ {797 if result[j].String() != expected[j] {798 t.Fatalf("Using key '%s' for '%s'\nexpected '%v', got '%v'",799 paths[j], which, expected[j], result[j].String())800 }801 }802 }803}804func TestIssue20(t *testing.T) {805 json := `{ "name": "FirstName", "name1": "FirstName1", ` +806 `"address": "address1", "addressDetails": "address2", }`807 paths := []string{"name", "name1", "address", "addressDetails"}808 expected := []string{"FirstName", "FirstName1", "address1", "address2"}809 t.Run("SingleMany", func(t *testing.T) {810 testMany(t, json, paths,811 expected)812 })813}814func TestIssue21(t *testing.T) {815 json := `{ "Level1Field1":3, 816 "Level1Field4":4, 817 "Level1Field2":{ "Level2Field1":[ "value1", "value2" ], 818 "Level2Field2":{ "Level3Field1":[ { "key1":"value1" } ] } } }`819 paths := []string{"Level1Field1", "Level1Field2.Level2Field1",820 "Level1Field2.Level2Field2.Level3Field1", "Level1Field4"}821 expected := []string{"3", `[ "value1", "value2" ]`,822 `[ { "key1":"value1" } ]`, "4"}823 t.Run("SingleMany", func(t *testing.T) {824 testMany(t, json, paths,825 expected)826 })827}828func TestRandomMany(t *testing.T) {829 var lstr string830 defer func() {831 if v := recover(); v != nil {832 println("'" + hex.EncodeToString([]byte(lstr)) + "'")833 println("'" + lstr + "'")834 panic(v)835 }836 }()837 rand.Seed(time.Now().UnixNano())838 b := make([]byte, 512)839 for i := 0; i < 50000; i++ {840 n, err := rand.Read(b[:rand.Int()%len(b)])841 if err != nil {842 t.Fatal(err)843 }844 lstr = string(b[:n])845 paths := make([]string, rand.Int()%64)846 for i := range paths {847 var b []byte848 n := rand.Int() % 5849 for j := 0; j < n; j++ {850 if j > 0 {851 b = append(b, '.')852 }853 nn := rand.Int() % 10854 for k := 0; k < nn; k++ {855 b = append(b, 'a'+byte(rand.Int()%26))856 }857 }858 paths[i] = string(b)859 }860 GetMany(lstr, paths...)861 }862}863type ComplicatedType struct {864 unsettable int865 Tagged string `json:"tagged"`866 NotTagged bool867 Nested struct {868 Yellow string `json:"yellow"`869 }870 NestedTagged struct {871 Green string872 Map map[string]interface{}873 Ints struct {874 Int int `json:"int"`875 Int8 int8876 Int16 int16877 Int32 int32878 Int64 int64 `json:"int64"`879 }880 Uints struct {881 Uint uint882 Uint8 uint8883 Uint16 uint16884 Uint32 uint32885 Uint64 uint64886 }887 Floats struct {888 Float64 float64889 Float32 float32890 }891 Byte byte892 Bool bool893 } `json:"nestedTagged"`894 LeftOut string `json:"-"`895 SelfPtr *ComplicatedType896 SelfSlice []ComplicatedType897 SelfSlicePtr []*ComplicatedType898 SelfPtrSlice *[]ComplicatedType899 Interface interface{} `json:"interface"`900 Array [3]int901 Time time.Time `json:"time"`902 Binary []byte903 NonBinary []byte904}905var complicatedJSON = `906{907 "tagged": "OK",908 "Tagged": "KO",909 "NotTagged": true,910 "unsettable": 101,911 "Nested": {912 "Yellow": "Green",913 "yellow": "yellow"914 },915 "nestedTagged": {916 "Green": "Green",917 "Map": {918 "this": "that", 919 "and": "the other thing"920 },921 "Ints": {922 "Uint": 99,923 "Uint16": 16,924 "Uint32": 32,925 "Uint64": 65926 },927 "Uints": {928 "int": -99,929 "Int": -98,930 "Int16": -16,931 "Int32": -32,932 "int64": -64,933 "Int64": -65934 },935 "Uints": {936 "Float32": 32.32,937 "Float64": 64.64938 },939 "Byte": 254,940 "Bool": true941 },942 "LeftOut": "you shouldn't be here",943 "SelfPtr": {"tagged":"OK","nestedTagged":{"Ints":{"Uint32":32}}},944 "SelfSlice": [{"tagged":"OK","nestedTagged":{"Ints":{"Uint32":32}}}],945 "SelfSlicePtr": [{"tagged":"OK","nestedTagged":{"Ints":{"Uint32":32}}}],946 "SelfPtrSlice": [{"tagged":"OK","nestedTagged":{"Ints":{"Uint32":32}}}],947 "interface": "Tile38 Rocks!",948 "Interface": "Please Download",949 "Array": [0,2,3,4,5],950 "time": "2017-05-07T13:24:43-07:00",951 "Binary": "R0lGODlhPQBEAPeo",952 "NonBinary": [9,3,100,115]953}954`955func testvalid(t *testing.T, json string, expect bool) {956 t.Helper()957 _, ok := validpayload([]byte(json), 0)958 if ok != expect {959 t.Fatal("mismatch")960 }961}962func TestValidBasic(t *testing.T) {963 testvalid(t, "0", true)964 testvalid(t, "00", false)965 testvalid(t, "-00", false)966 testvalid(t, "-.", false)967 testvalid(t, "0.0", true)968 testvalid(t, "10.0", true)969 testvalid(t, "10e1", true)970 testvalid(t, "10EE", false)971 testvalid(t, "10E-", false)972 testvalid(t, "10E+", false)973 testvalid(t, "10E123", true)974 testvalid(t, "10E-123", true)975 testvalid(t, "10E-0123", true)976 testvalid(t, "", false)977 testvalid(t, " ", false)978 testvalid(t, "{}", true)979 testvalid(t, "{", false)980 testvalid(t, "-", false)981 testvalid(t, "-1", true)982 testvalid(t, "-1.", false)983 testvalid(t, "-1.0", true)984 testvalid(t, " -1.0", true)985 testvalid(t, " -1.0 ", true)986 testvalid(t, "-1.0 ", true)987 testvalid(t, "-1.0 i", false)988 testvalid(t, "-1.0 i", false)989 testvalid(t, "true", true)990 testvalid(t, " true", true)991 testvalid(t, " true ", true)992 testvalid(t, " True ", false)993 testvalid(t, " tru", false)994 testvalid(t, "false", true)995 testvalid(t, " false", true)996 testvalid(t, " false ", true)997 testvalid(t, " False ", false)998 testvalid(t, " fals", false)999 testvalid(t, "null", true)1000 testvalid(t, " null", true)1001 testvalid(t, " null ", true)1002 testvalid(t, " Null ", false)1003 testvalid(t, " nul", false)1004 testvalid(t, " []", true)1005 testvalid(t, " [true]", true)1006 testvalid(t, " [ true, null ]", true)1007 testvalid(t, " [ true,]", false)1008 testvalid(t, `{"hello":"world"}`, true)1009 testvalid(t, `{ "hello": "world" }`, true)1010 testvalid(t, `{ "hello": "world", }`, false)1011 testvalid(t, `{"a":"b",}`, false)1012 testvalid(t, `{"a":"b","a"}`, false)1013 testvalid(t, `{"a":"b","a":}`, false)1014 testvalid(t, `{"a":"b","a":1}`, true)1015 testvalid(t, `{"a":"b",2"1":2}`, false)1016 testvalid(t, `{"a":"b","a": 1, "c":{"hi":"there"} }`, true)1017 testvalid(t, `{"a":"b","a": 1, "c":{"hi":"there", "easy":["going",`+1018 `{"mixed":"bag"}]} }`, true)1019 testvalid(t, `""`, true)1020 testvalid(t, `"`, false)1021 testvalid(t, `"\n"`, true)1022 testvalid(t, `"\"`, false)1023 testvalid(t, `"\\"`, true)1024 testvalid(t, `"a\\b"`, true)1025 testvalid(t, `"a\\b\\\"a"`, true)1026 testvalid(t, `"a\\b\\\uFFAAa"`, true)1027 testvalid(t, `"a\\b\\\uFFAZa"`, false)1028 testvalid(t, `"a\\b\\\uFFA"`, false)1029 testvalid(t, string(complicatedJSON), true)1030 testvalid(t, string(exampleJSON), true)1031}1032var jsonchars = []string{"{", "[", ",", ":", "}", "]", "1", "0", "true",1033 "false", "null", `""`, `"\""`, `"a"`}1034func makeRandomJSONChars(b []byte) {1035 var bb []byte1036 for len(bb) < len(b) {1037 bb = append(bb, jsonchars[rand.Int()%len(jsonchars)]...)1038 }1039 copy(b, bb[:len(b)])1040}1041func TestValidRandom(t *testing.T) {1042 rand.Seed(time.Now().UnixNano())1043 b := make([]byte, 100000)1044 start := time.Now()1045 for time.Since(start) < time.Second*3 {1046 n := rand.Int() % len(b)1047 rand.Read(b[:n])1048 validpayload(b[:n], 0)1049 }1050 start = time.Now()1051 for time.Since(start) < time.Second*3 {1052 n := rand.Int() % len(b)1053 makeRandomJSONChars(b[:n])1054 validpayload(b[:n], 0)1055 }1056}1057func TestGetMany47(t *testing.T) {1058 json := `{"bar": {"id": 99, "mybar": "my mybar" }, "foo": ` +1059 `{"myfoo": [605]}}`1060 paths := []string{"foo.myfoo", "bar.id", "bar.mybar", "bar.mybarx"}1061 expected := []string{"[605]", "99", "my mybar", ""}1062 results := GetMany(json, paths...)1063 if len(expected) != len(results) {1064 t.Fatalf("expected %v, got %v", len(expected), len(results))1065 }1066 for i, path := range paths {1067 if results[i].String() != expected[i] {1068 t.Fatalf("expected '%v', got '%v' for path '%v'", expected[i],1069 results[i].String(), path)1070 }1071 }1072}1073func TestGetMany48(t *testing.T) {1074 json := `{"bar": {"id": 99, "xyz": "my xyz"}, "foo": {"myfoo": [605]}}`1075 paths := []string{"foo.myfoo", "bar.id", "bar.xyz", "bar.abc"}1076 expected := []string{"[605]", "99", "my xyz", ""}1077 results := GetMany(json, paths...)1078 if len(expected) != len(results) {1079 t.Fatalf("expected %v, got %v", len(expected), len(results))1080 }1081 for i, path := range paths {1082 if results[i].String() != expected[i] {1083 t.Fatalf("expected '%v', got '%v' for path '%v'", expected[i],1084 results[i].String(), path)1085 }1086 }1087}1088func TestResultRawForLiteral(t *testing.T) {1089 for _, lit := range []string{"null", "true", "false"} {1090 result := Parse(lit)1091 if result.Raw != lit {1092 t.Fatalf("expected '%v', got '%v'", lit, result.Raw)1093 }1094 }1095}1096func TestNullArray(t *testing.T) {1097 n := len(Get(`{"data":null}`, "data").Array())1098 if n != 0 {1099 t.Fatalf("expected '%v', got '%v'", 0, n)1100 }1101 n = len(Get(`{}`, "data").Array())1102 if n != 0 {1103 t.Fatalf("expected '%v', got '%v'", 0, n)1104 }1105 n = len(Get(`{"data":[]}`, "data").Array())1106 if n != 0 {1107 t.Fatalf("expected '%v', got '%v'", 0, n)1108 }1109 n = len(Get(`{"data":[null]}`, "data").Array())1110 if n != 1 {1111 t.Fatalf("expected '%v', got '%v'", 1, n)1112 }1113}1114// func TestRandomGetMany(t *testing.T) {1115// start := time.Now()1116// for time.Since(start) < time.Second*3 {1117// testRandomGetMany(t)1118// }1119// }1120func testRandomGetMany(t *testing.T) {1121 rand.Seed(time.Now().UnixNano())1122 json, keys := randomJSON()1123 for _, key := range keys {1124 r := Get(json, key)1125 if !r.Exists() {1126 t.Fatal("should exist")1127 }1128 }1129 rkeysi := rand.Perm(len(keys))1130 rkeysn := 1 + rand.Int()%321131 if len(rkeysi) > rkeysn {1132 rkeysi = rkeysi[:rkeysn]1133 }1134 var rkeys []string1135 for i := 0; i < len(rkeysi); i++ {1136 rkeys = append(rkeys, keys[rkeysi[i]])1137 }1138 mres1 := GetMany(json, rkeys...)1139 var mres2 []Result1140 for _, rkey := range rkeys {1141 mres2 = append(mres2, Get(json, rkey))1142 }1143 if len(mres1) != len(mres2) {1144 t.Fatalf("expected %d, got %d", len(mres2), len(mres1))1145 }1146 for i := 0; i < len(mres1); i++ {1147 mres1[i].Index = 01148 mres2[i].Index = 01149 v1 := fmt.Sprintf("%#v", mres1[i])1150 v2 := fmt.Sprintf("%#v", mres2[i])1151 if v1 != v2 {1152 t.Fatalf("\nexpected %s\n"+1153 " got %s", v2, v1)1154 }1155 }1156}1157func TestIssue54(t *testing.T) {1158 var r []Result1159 json := `{"MarketName":null,"Nounce":6115}`1160 r = GetMany(json, "Nounce", "Buys", "Sells", "Fills")1161 if strings.Replace(fmt.Sprintf("%v", r), " ", "", -1) != "[6115]" {1162 t.Fatalf("expected '%v', got '%v'", "[6115]",1163 strings.Replace(fmt.Sprintf("%v", r), " ", "", -1))1164 }1165 r = GetMany(json, "Nounce", "Buys", "Sells")1166 if strings.Replace(fmt.Sprintf("%v", r), " ", "", -1) != "[6115]" {1167 t.Fatalf("expected '%v', got '%v'", "[6115]",1168 strings.Replace(fmt.Sprintf("%v", r), " ", "", -1))1169 }1170 r = GetMany(json, "Nounce")1171 if strings.Replace(fmt.Sprintf("%v", r), " ", "", -1) != "[6115]" {1172 t.Fatalf("expected '%v', got '%v'", "[6115]",1173 strings.Replace(fmt.Sprintf("%v", r), " ", "", -1))1174 }1175}1176func randomString() string {1177 var key string1178 N := 1 + rand.Int()%161179 for i := 0; i < N; i++ {1180 r := rand.Int() % 621181 if r < 10 {1182 key += string(byte('0' + r))1183 } else if r-10 < 26 {1184 key += string(byte('a' + r - 10))1185 } else {1186 key += string(byte('A' + r - 10 - 26))1187 }1188 }1189 return `"` + key + `"`1190}1191func randomBool() string {1192 switch rand.Int() % 2 {1193 default:1194 return "false"1195 case 1:1196 return "true"1197 }1198}1199func randomNumber() string {1200 return strconv.FormatInt(int64(rand.Int()%1000000), 10)1201}1202func randomObjectOrArray(keys []string, prefix string, array bool, depth int) (1203 string, []string) {1204 N := 5 + rand.Int()%51205 var json string1206 if array {1207 json = "["1208 } else {1209 json = "{"1210 }1211 for i := 0; i < N; i++ {1212 if i > 0 {1213 json += ","1214 }1215 var pkey string1216 if array {1217 pkey = prefix + "." + strconv.FormatInt(int64(i), 10)1218 } else {1219 key := randomString()1220 pkey = prefix + "." + key[1:len(key)-1]1221 json += key + `:`1222 }1223 keys = append(keys, pkey[1:])1224 var kind int1225 if depth == 5 {1226 kind = rand.Int() % 41227 } else {1228 kind = rand.Int() % 61229 }1230 switch kind {1231 case 0:1232 json += randomString()1233 case 1:1234 json += randomBool()1235 case 2:1236 json += "null"1237 case 3:1238 json += randomNumber()1239 case 4:1240 var njson string1241 njson, keys = randomObjectOrArray(keys, pkey, true, depth+1)1242 json += njson1243 case 5:1244 var njson string1245 njson, keys = randomObjectOrArray(keys, pkey, false, depth+1)1246 json += njson1247 }1248 }1249 if array {1250 json += "]"1251 } else {1252 json += "}"1253 }1254 return json, keys1255}1256func randomJSON() (json string, keys []string) {1257 return randomObjectOrArray(nil, "", false, 0)1258}1259func TestIssue55(t *testing.T) {1260 json := `{"one": {"two": 2, "three": 3}, "four": 4, "five": 5}`1261 results := GetMany(json, "four", "five", "one.two", "one.six")1262 expected := []string{"4", "5", "2", ""}1263 for i, r := range results {1264 if r.String() != expected[i] {1265 t.Fatalf("expected %v, got %v", expected[i], r.String())1266 }1267 }1268}1269func TestIssue58(t *testing.T) {1270 json := `{"data":[{"uid": 1},{"uid": 2}]}`1271 res := Get(json, `data.#[uid!=1]`).Raw1272 if res != `{"uid": 2}` {1273 t.Fatalf("expected '%v', got '%v'", `{"uid": 1}`, res)1274 }1275}1276func TestObjectGrouping(t *testing.T) {1277 json := `1278[1279 true,1280 {"name":"tom"},1281 false,1282 {"name":"janet"},1283 null1284]1285`1286 res := Get(json, "#.name")1287 if res.String() != `["tom","janet"]` {1288 t.Fatalf("expected '%v', got '%v'", `["tom","janet"]`, res.String())1289 }1290}1291func TestJSONLines(t *testing.T) {1292 json := `1293true1294false1295{"name":"tom"}1296[1,2,3,4,5]1297{"name":"janet"}1298null129912930.12031300 `1301 paths := []string{"..#", "..0", "..2.name", "..#.name", "..6", "..7"}1302 ress := []string{"7", "true", "tom", `["tom","janet"]`, "12930.1203", ""}1303 for i, path := range paths {1304 res := Get(json, path)1305 if res.String() != ress[i] {1306 t.Fatalf("expected '%v', got '%v'", ress[i], res.String())1307 }1308 }1309 json = `1310{"name": "Gilbert", "wins": [["straight", "7â£"], ["one pair", "10â¥"]]}1311{"name": "Alexa", "wins": [["two pair", "4â "], ["two pair", "9â "]]}1312{"name": "May", "wins": []}1313{"name": "Deloise", "wins": [["three of a kind", "5â£"]]}1314`1315 var i int1316 lines := strings.Split(strings.TrimSpace(json), "\n")1317 ForEachLine(json, func(line Result) bool {1318 if line.Raw != lines[i] {1319 t.Fatalf("expected '%v', got '%v'", lines[i], line.Raw)1320 }1321 i++1322 return true1323 })1324 if i != 4 {1325 t.Fatalf("expected '%v', got '%v'", 4, i)1326 }1327}1328func TestNumUint64String(t *testing.T) {1329 var i int64 = 9007199254740993 //2^53 + 11330 j := fmt.Sprintf(`{"data": [ %d, "hello" ] }`, i)1331 res := Get(j, "data.0")1332 if res.String() != "9007199254740993" {1333 t.Fatalf("expected '%v', got '%v'", "9007199254740993", res.String())1334 }1335}1336func TestNumInt64String(t *testing.T) {1337 var i int64 = -90071992547409931338 j := fmt.Sprintf(`{"data":[ "hello", %d ]}`, i)1339 res := Get(j, "data.1")1340 if res.String() != "-9007199254740993" {1341 t.Fatalf("expected '%v', got '%v'", "-9007199254740993", res.String())1342 }1343}1344func TestNumBigString(t *testing.T) {1345 i := "900719925474099301239109123101" // very big1346 j := fmt.Sprintf(`{"data":[ "hello", "%s" ]}`, i)1347 res := Get(j, "data.1")1348 if res.String() != "900719925474099301239109123101" {1349 t.Fatalf("expected '%v', got '%v'", "900719925474099301239109123101",1350 res.String())1351 }1352}1353func TestNumFloatString(t *testing.T) {1354 var i int64 = -90071992547409931355 j := fmt.Sprintf(`{"data":[ "hello", %d ]}`, i) //No quotes around value!!1356 res := Get(j, "data.1")1357 if res.String() != "-9007199254740993" {1358 t.Fatalf("expected '%v', got '%v'", "-9007199254740993", res.String())1359 }1360}1361func TestDuplicateKeys(t *testing.T) {1362 // this is vaild json according to the JSON spec1363 var json = `{"name": "Alex","name": "Peter"}`1364 if Parse(json).Get("name").String() !=1365 Parse(json).Map()["name"].String() {1366 t.Fatalf("expected '%v', got '%v'",1367 Parse(json).Get("name").String(),1368 Parse(json).Map()["name"].String(),1369 )1370 }1371 if !Valid(json) {1372 t.Fatal("should be valid")1373 }1374}1375func TestArrayValues(t *testing.T) {1376 var json = `{"array": ["PERSON1","PERSON2",0],}`1377 values := Get(json, "array").Array()1378 var output string1379 for i, val := range values {1380 if i > 0 {1381 output += "\n"1382 }1383 output += fmt.Sprintf("%#v", val)1384 }1385 expect := strings.Join([]string{1386 `gjson.Result{Type:3, Raw:"\"PERSON1\"", Str:"PERSON1", Num:0, ` +1387 `Index:0}`,1388 `gjson.Result{Type:3, Raw:"\"PERSON2\"", Str:"PERSON2", Num:0, ` +1389 `Index:0}`,1390 `gjson.Result{Type:2, Raw:"0", Str:"", Num:0, Index:0}`,1391 }, "\n")1392 if output != expect {1393 t.Fatalf("expected '%v', got '%v'", expect, output)1394 }1395}1396func BenchmarkValid(b *testing.B) {1397 for i := 0; i < b.N; i++ {1398 Valid(complicatedJSON)1399 }1400}1401func BenchmarkValidBytes(b *testing.B) {1402 complicatedJSON := []byte(complicatedJSON)1403 for i := 0; i < b.N; i++ {1404 ValidBytes(complicatedJSON)1405 }1406}1407func BenchmarkGoStdlibValidBytes(b *testing.B) {1408 complicatedJSON := []byte(complicatedJSON)1409 for i := 0; i < b.N; i++ {1410 json.Valid(complicatedJSON)1411 }1412}1413func TestModifier(t *testing.T) {1414 json := `{"other":{"hello":"world"},"arr":[1,2,3,4,5,6]}`1415 opts := *pretty.DefaultOptions1416 opts.SortKeys = true1417 exp := string(pretty.PrettyOptions([]byte(json), &opts))1418 res := Get(json, `@pretty:{"sortKeys":true}`).String()1419 if res != exp {1420 t.Fatalf("expected '%v', got '%v'", exp, res)1421 }1422 res = Get(res, "@pretty|@reverse|@ugly").String()1423 if res != json {1424 t.Fatalf("expected '%v', got '%v'", json, res)...
decode_test.go
Source:decode_test.go
...284 {V: EOF},285 {V: EOF},286 },287 },288 // JSON literals.289 {290 in: space + `null` + space,291 want: []R{292 {V: Null, P: len(space), RS: `null`},293 {V: EOF},294 },295 },296 {297 in: space + `true` + space,298 want: []R{299 {V: Bool{true}},300 {V: EOF},301 },302 },303 {304 in: space + `false` + space,305 want: []R{306 {V: Bool{false}},307 {V: EOF},308 },309 },310 {311 // Error returned will produce the same error again.312 in: space + `foo` + space,313 want: []R{314 {E: `invalid value foo`},315 {E: `invalid value foo`},316 },317 },318 // JSON strings.319 {320 in: space + `""` + space,321 want: []R{322 {V: Str{}},323 {V: EOF},324 },325 },326 {327 in: space + `"hello"` + space,328 want: []R{329 {V: Str{"hello"}, RS: `"hello"`},330 {V: EOF},331 },332 },333 {334 in: `"hello`,335 want: []R{{E: errEOF}},336 },337 {338 in: "\"\x00\"",339 want: []R{{E: `invalid character '\x00' in string`}},340 },341 {342 in: "\"\u0031\u0032\"",343 want: []R{344 {V: Str{"12"}, RS: "\"\u0031\u0032\""},345 {V: EOF},346 },347 },348 {349 // Invalid UTF-8 error is returned in ReadString instead of Read.350 in: "\"\xff\"",351 want: []R{{E: `syntax error (line 1:1): invalid UTF-8 in string`}},352 },353 {354 in: `"` + string(utf8.RuneError) + `"`,355 want: []R{356 {V: Str{string(utf8.RuneError)}},357 {V: EOF},358 },359 },360 {361 in: `"\uFFFD"`,362 want: []R{363 {V: Str{string(utf8.RuneError)}},364 {V: EOF},365 },366 },367 {368 in: `"\x"`,369 want: []R{{E: `invalid escape code "\\x" in string`}},370 },371 {372 in: `"\uXXXX"`,373 want: []R{{E: `invalid escape code "\\uXXXX" in string`}},374 },375 {376 in: `"\uDEAD"`, // unmatched surrogate pair377 want: []R{{E: errEOF}},378 },379 {380 in: `"\uDEAD\uBEEF"`, // invalid surrogate half381 want: []R{{E: `invalid escape code "\\uBEEF" in string`}},382 },383 {384 in: `"\uD800\udead"`, // valid surrogate pair385 want: []R{386 {V: Str{`ð`}},387 {V: EOF},388 },389 },390 {391 in: `"\u0000\"\\\/\b\f\n\r\t"`,392 want: []R{393 {V: Str{"\u0000\"\\/\b\f\n\r\t"}},394 {V: EOF},395 },396 },397 // Invalid JSON numbers.398 {399 in: `-`,400 want: []R{{E: `invalid value -`}},401 },402 {403 in: `+0`,404 want: []R{{E: `invalid value +0`}},405 },406 {407 in: `-+`,408 want: []R{{E: `invalid value -+`}},409 },410 {411 in: `0.`,412 want: []R{{E: `invalid value 0.`}},413 },414 {415 in: `.1`,416 want: []R{{E: `invalid value .1`}},417 },418 {419 in: `1.0.1`,420 want: []R{{E: `invalid value 1.0.1`}},421 },422 {423 in: `1..1`,424 want: []R{{E: `invalid value 1..1`}},425 },426 {427 in: `-1-2`,428 want: []R{{E: `invalid value -1-2`}},429 },430 {431 in: `01`,432 want: []R{{E: `invalid value 01`}},433 },434 {435 in: `1e`,436 want: []R{{E: `invalid value 1e`}},437 },438 {439 in: `1e1.2`,440 want: []R{{E: `invalid value 1e1.2`}},441 },442 {443 in: `1Ee`,444 want: []R{{E: `invalid value 1Ee`}},445 },446 {447 in: `1.e1`,448 want: []R{{E: `invalid value 1.e1`}},449 },450 {451 in: `1.e+`,452 want: []R{{E: `invalid value 1.e+`}},453 },454 {455 in: `1e+-2`,456 want: []R{{E: `invalid value 1e+-2`}},457 },458 {459 in: `1e--2`,460 want: []R{{E: `invalid value 1e--2`}},461 },462 {463 in: `1.0true`,464 want: []R{{E: `invalid value 1.0true`}},465 },466 // JSON numbers as floating point.467 {468 in: space + `0.0` + space,469 want: []R{470 {V: F32{0}, P: len(space), RS: `0.0`},471 {V: EOF},472 },473 },474 {475 in: space + `0` + space,476 want: []R{477 {V: F32{0}},478 {V: EOF},479 },480 },481 {482 in: space + `-0` + space,483 want: []R{484 {V: F32{float32(math.Copysign(0, -1))}},485 {V: EOF},486 },487 },488 {489 in: `-0`,490 want: []R{491 {V: F64{math.Copysign(0, -1)}},492 {V: EOF},493 },494 },495 {496 in: `-0.0`,497 want: []R{498 {V: F32{float32(math.Copysign(0, -1))}},499 {V: EOF},500 },501 },502 {503 in: `-0.0`,504 want: []R{505 {V: F64{math.Copysign(0, -1)}},506 {V: EOF},507 },508 },509 {510 in: `-1.02`,511 want: []R{512 {V: F32{-1.02}},513 {V: EOF},514 },515 },516 {517 in: `1.020000`,518 want: []R{519 {V: F32{1.02}},520 {V: EOF},521 },522 },523 {524 in: `-1.0e0`,525 want: []R{526 {V: F32{-1}},527 {V: EOF},528 },529 },530 {531 in: `1.0e-000`,532 want: []R{533 {V: F32{1}},534 {V: EOF},535 },536 },537 {538 in: `1e+00`,539 want: []R{540 {V: F32{1}},541 {V: EOF},542 },543 },544 {545 in: `1.02e3`,546 want: []R{547 {V: F32{1.02e3}},548 {V: EOF},549 },550 },551 {552 in: `-1.02E03`,553 want: []R{554 {V: F32{-1.02e3}},555 {V: EOF},556 },557 },558 {559 in: `1.0200e+3`,560 want: []R{561 {V: F32{1.02e3}},562 {V: EOF},563 },564 },565 {566 in: `-1.0200E+03`,567 want: []R{568 {V: F32{-1.02e3}},569 {V: EOF},570 },571 },572 {573 in: `1.0200e-3`,574 want: []R{575 {V: F32{1.02e-3}},576 {V: EOF},577 },578 },579 {580 in: `-1.0200E-03`,581 want: []R{582 {V: F32{-1.02e-3}},583 {V: EOF},584 },585 },586 {587 // Exceeds max float32 limit, but should be ok for float64.588 in: `3.4e39`,589 want: []R{590 {V: F64{3.4e39}},591 {V: EOF},592 },593 },594 {595 // Exceeds max float32 limit.596 in: `3.4e39`,597 want: []R{598 {V: NotF32},599 {V: EOF},600 },601 },602 {603 // Less than negative max float32 limit.604 in: `-3.4e39`,605 want: []R{606 {V: NotF32},607 {V: EOF},608 },609 },610 {611 // Exceeds max float64 limit.612 in: `1.79e+309`,613 want: []R{614 {V: NotF64},615 {V: EOF},616 },617 },618 {619 // Less than negative max float64 limit.620 in: `-1.79e+309`,621 want: []R{622 {V: NotF64},623 {V: EOF},624 },625 },626 // JSON numbers as signed integers.627 {628 in: space + `0` + space,629 want: []R{630 {V: I32{0}},631 {V: EOF},632 },633 },634 {635 in: space + `-0` + space,636 want: []R{637 {V: I32{0}},638 {V: EOF},639 },640 },641 {642 // Fractional part equals 0 is ok.643 in: `1.00000`,644 want: []R{645 {V: I32{1}},646 {V: EOF},647 },648 },649 {650 // Fractional part not equals 0 returns error.651 in: `1.0000000001`,652 want: []R{653 {V: NotI32},654 {V: EOF},655 },656 },657 {658 in: `0e0`,659 want: []R{660 {V: I32{0}},661 {V: EOF},662 },663 },664 {665 in: `0.0E0`,666 want: []R{667 {V: I32{0}},668 {V: EOF},669 },670 },671 {672 in: `0.0E10`,673 want: []R{674 {V: I32{0}},675 {V: EOF},676 },677 },678 {679 in: `-1`,680 want: []R{681 {V: I32{-1}},682 {V: EOF},683 },684 },685 {686 in: `1.0e+0`,687 want: []R{688 {V: I32{1}},689 {V: EOF},690 },691 },692 {693 in: `-1E-0`,694 want: []R{695 {V: I32{-1}},696 {V: EOF},697 },698 },699 {700 in: `1E1`,701 want: []R{702 {V: I32{10}},703 {V: EOF},704 },705 },706 {707 in: `-100.00e-02`,708 want: []R{709 {V: I32{-1}},710 {V: EOF},711 },712 },713 {714 in: `0.1200E+02`,715 want: []R{716 {V: I64{12}},717 {V: EOF},718 },719 },720 {721 in: `0.012e2`,722 want: []R{723 {V: NotI32},724 {V: EOF},725 },726 },727 {728 in: `12e-2`,729 want: []R{730 {V: NotI32},731 {V: EOF},732 },733 },734 {735 // Exceeds math.MaxInt32.736 in: `2147483648`,737 want: []R{738 {V: NotI32},739 {V: EOF},740 },741 },742 {743 // Exceeds math.MinInt32.744 in: `-2147483649`,745 want: []R{746 {V: NotI32},747 {V: EOF},748 },749 },750 {751 // Exceeds math.MaxInt32, but ok for int64.752 in: `2147483648`,753 want: []R{754 {V: I64{2147483648}},755 {V: EOF},756 },757 },758 {759 // Exceeds math.MinInt32, but ok for int64.760 in: `-2147483649`,761 want: []R{762 {V: I64{-2147483649}},763 {V: EOF},764 },765 },766 {767 // Exceeds math.MaxInt64.768 in: `9223372036854775808`,769 want: []R{770 {V: NotI64},771 {V: EOF},772 },773 },774 {775 // Exceeds math.MinInt64.776 in: `-9223372036854775809`,777 want: []R{778 {V: NotI64},779 {V: EOF},780 },781 },782 // JSON numbers as unsigned integers.783 {784 in: space + `0` + space,785 want: []R{786 {V: Ui32{0}},787 {V: EOF},788 },789 },790 {791 in: space + `-0` + space,792 want: []R{793 {V: Ui32{0}},794 {V: EOF},795 },796 },797 {798 in: `-1`,799 want: []R{800 {V: NotUi32},801 {V: EOF},802 },803 },804 {805 // Exceeds math.MaxUint32.806 in: `4294967296`,807 want: []R{808 {V: NotUi32},809 {V: EOF},810 },811 },812 {813 // Exceeds math.MaxUint64.814 in: `18446744073709551616`,815 want: []R{816 {V: NotUi64},817 {V: EOF},818 },819 },820 // JSON sequence of values.821 {822 in: `true null`,823 want: []R{824 {V: Bool{true}},825 {E: `(line 1:6): unexpected token null`},826 },827 },828 {829 in: "null false",830 want: []R{831 {V: Null},832 {E: `unexpected token false`},833 },834 },835 {836 in: `true,false`,837 want: []R{838 {V: Bool{true}},839 {E: `unexpected token ,`},840 },841 },842 {843 in: `47"hello"`,844 want: []R{845 {V: I32{47}},846 {E: `unexpected token "hello"`},847 },848 },849 {850 in: `47 "hello"`,851 want: []R{852 {V: I32{47}},853 {E: `unexpected token "hello"`},854 },855 },856 {857 in: `true 42`,858 want: []R{859 {V: Bool{true}},860 {E: `unexpected token 42`},861 },862 },863 // JSON arrays.864 {865 in: space + `[]` + space,866 want: []R{867 {V: ArrayOpen},868 {V: ArrayClose},869 {V: EOF},870 },871 },872 {873 in: space + `[` + space + `]` + space,874 want: []R{875 {V: ArrayOpen, P: len(space), RS: `[`},876 {V: ArrayClose},877 {V: EOF},878 },879 },880 {881 in: space + `[` + space,882 want: []R{883 {V: ArrayOpen},884 {E: errEOF},885 },886 },887 {888 in: space + `]` + space,889 want: []R{{E: `unexpected token ]`}},890 },891 {892 in: `[null,true,false, 1e1, "hello" ]`,893 want: []R{894 {V: ArrayOpen},895 {V: Null},896 {V: Bool{true}},897 {V: Bool{false}},898 {V: I32{10}},899 {V: Str{"hello"}},900 {V: ArrayClose},901 {V: EOF},902 },903 },904 {905 in: `[` + space + `true` + space + `,` + space + `"hello"` + space + `]`,906 want: []R{907 {V: ArrayOpen},908 {V: Bool{true}},909 {V: Str{"hello"}},910 {V: ArrayClose},911 {V: EOF},912 },913 },914 {915 in: `[` + space + `true` + space + `,` + space + `]`,916 want: []R{917 {V: ArrayOpen},918 {V: Bool{true}},919 {E: `unexpected token ]`},920 },921 },922 {923 in: `[` + space + `false` + space + `]`,924 want: []R{925 {V: ArrayOpen},926 {V: Bool{false}},927 {V: ArrayClose},928 {V: EOF},929 },930 },931 {932 in: `[` + space + `1` + space + `0` + space + `]`,933 want: []R{934 {V: ArrayOpen},935 {V: I64{1}},936 {E: `unexpected token 0`},937 },938 },939 {940 in: `[null`,941 want: []R{942 {V: ArrayOpen},943 {V: Null},944 {E: errEOF},945 },946 },947 {948 in: `[foo]`,949 want: []R{950 {V: ArrayOpen},951 {E: `invalid value foo`},952 },953 },954 {955 in: `[{}, "hello", [true, false], null]`,956 want: []R{957 {V: ArrayOpen},958 {V: ObjectOpen},959 {V: ObjectClose},960 {V: Str{"hello"}},961 {V: ArrayOpen},962 {V: Bool{true}},963 {V: Bool{false}},964 {V: ArrayClose},965 {V: Null},966 {V: ArrayClose},967 {V: EOF},968 },969 },970 {971 in: `[{ ]`,972 want: []R{973 {V: ArrayOpen},974 {V: ObjectOpen},975 {E: `unexpected token ]`},976 },977 },978 {979 in: `[[ ]`,980 want: []R{981 {V: ArrayOpen},982 {V: ArrayOpen},983 {V: ArrayClose},984 {E: errEOF},985 },986 },987 {988 in: `[,]`,989 want: []R{990 {V: ArrayOpen},991 {E: `unexpected token ,`},992 },993 },994 {995 in: `[true "hello"]`,996 want: []R{997 {V: ArrayOpen},998 {V: Bool{true}},999 {E: `unexpected token "hello"`},1000 },1001 },1002 {1003 in: `[] null`,1004 want: []R{1005 {V: ArrayOpen},1006 {V: ArrayClose},1007 {E: `unexpected token null`},1008 },1009 },1010 {1011 in: `true []`,1012 want: []R{1013 {V: Bool{true}},1014 {E: `unexpected token [`},1015 },1016 },1017 // JSON objects.1018 {1019 in: space + `{}` + space,1020 want: []R{1021 {V: ObjectOpen},1022 {V: ObjectClose},1023 {V: EOF},1024 },1025 },1026 {1027 in: space + `{` + space + `}` + space,1028 want: []R{1029 {V: ObjectOpen},1030 {V: ObjectClose},1031 {V: EOF},...
JSON
Using AI Code Generation
1import (2type person struct {3}4func main() {5 p1 := person{"James", "Bond", 20}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T9 fmt.Println(string(bs))10}11{"First":"James","Last":"Bond","Age":20}12import (13type person struct {14}15func main() {16 p1 := person{"James", "Bond", 20}17 bs, _ := json.Marshal(p1)18 fmt.Println(bs)19 fmt.Printf("%T20 fmt.Println(string(bs))21}22{"First":"James","Last":"Bond","Age":20}23import (24type person struct {25}26func main() {27 p1 := person{"James", "Bond", 20}28 bs, _ := json.Marshal(p1)29 fmt.Println(bs)30 fmt.Printf("%T31 fmt.Println(string(bs))32}
JSON
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", "Bond", 20, 007}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T9 fmt.Println(string(bs))10}11import (12type Person struct {13}14func main() {15 p1 := Person{"James", "Bond", 20, 007}16 bs, _ := json.Marshal(p1)17 fmt.Println(bs)18 fmt.Printf("%T19 fmt.Println(string(bs))20}
JSON
Using AI Code Generation
1import (2type Person struct {3}4func main() {5 p1 := Person{"James", 20}6 bs, _ := json.Marshal(p1)7 fmt.Println(bs)8 fmt.Printf("%T", bs)9 fmt.Println(string(bs))10}11{"Age":20,"Name":"James"}12func Unmarshal(data []byte, v interface{})
JSON
Using AI Code Generation
1import (2func main() {3 type got struct {4 }5 got1 := got{"Jon", 32, 6, 200}6 got2 := got{"Sansa", 16, 5, 100}7 got3 := got{"Arya", 16, 5, 100}8 got4 := got{"Bran", 10, 4, 75}9 got5 := got{"Theon", 16, 5, 100}10 got6 := got{"Tyrion", 32, 4, 150}11 got7 := got{"Samwell", 32, 4, 150}12 got8 := got{"Jorah", 32, 4, 150}13 got9 := got{"Davos", 32, 4, 150}14 got10 := got{"Gendry", 32, 4, 150}15 got11 := got{"Brienne", 32, 4, 150}16 got12 := got{"Podrick", 32, 4, 150}17 got13 := got{"Edd", 32, 4, 150}18 got14 := got{"Gilly", 32, 4, 150}19 got15 := got{"Melisandre", 32, 4, 150}20 got16 := got{"Varys", 32, 4, 150}21 got17 := got{"Tormund", 32, 4, 150}22 got18 := got{"Yara", 32, 4, 150}23 got19 := got{"Gilly", 32, 4, 150}24 got20 := got{"Jaqen", 32, 4, 150}25 got21 := got{"Bronn", 32, 4, 150}26 got22 := got{"Euron", 32, 4, 150}27 got23 := got{"Missandei", 32, 4, 150}28 got24 := got{"Gendry", 32, 4, 150}29 got25 := got{"The Hound", 32,
JSON
Using AI Code Generation
1func main() {2 got.Family = []string{"Robb", "Sansa", "Arya", "Bran", "Rickon"}3 got.Skills = map[string]string{"sword": "Ice", "animal": "Ghost"}4 got.Born = GOTDate{Day: 17, Month: 12, Year: 283}5 got.Died = GOTDate{Day: 9, Month: 5, Year: 299}6 got.Children = []string{}7 got.Parents = []string{"Ned", "Catelyn"}8 got.Lovers = []string{}9 got.Allegiances = []string{"House Stark", "Night's Watch"}10 got.Titles = []string{"Lord Commander of the Night's Watch", "King in the North"}11 got.Books = []string{"A Game of Thrones", "A Clash of Kings", "A Storm of Swords", "A Feast for Crows", "A Dance with Dragons"}12 got.PovBooks = []string{"A Game of Thrones", "A Clash of Kings", "A Storm of Swords", "A Feast for Crows", "A Dance with Dragons"}13 got.TvSeries = []string{"Season 1", "Season 2", "Season 3", "Season 4", "Season 5", "Season 6"}14 got.PlayedBy = []string{"Kit Harington"}15 b, err := json.Marshal(got)16 if err != nil {17 fmt.Println(err)18 }19 os.Stdout.Write(b)20}21{"Name":"Jon Snow","Surname":"Snow","Age":25,"IsAlive":true,"Family":["Robb","Sansa","Arya","Bran","Rickon"],"Skills":{"sword":"Ice","animal":"Ghost"},"Born":{"Day":17,"Month":12,"Year":283},"Died":{"Day":9,"Month":5,"Year":299},"Married":false,"Spouse":"","Children":[],"Parents":["Ned","Catelyn"],"Lovers
JSON
Using AI Code Generation
1got.JSON()2got.XML()3got.CSV()4import (5func main() {6 fmt.Println(got.JSON())7 fmt.Println(got.XML())8 fmt.Println(got.CSV())9}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!