tidwall / gjson

Get JSON values quickly - JSON parser for Go
MIT License
14.4k stars 858 forks source link

Why is the key 0 #361

Open vaecou opened 5 months ago

vaecou commented 5 months ago

image

func TestParseJSON(t *testing.T) { str :=[ {"drawNumber":"51117487"}, {"drawNumber":"51117486"}, {"drawNumber":"51117485"}, {"drawNumber":"51117484"}, {"drawNumber":"51117483"}, {"drawNumber":"51117482"}, {"drawNumber":"51117481"}, {"drawNumber":"51117480"}, {"drawNumber":"51117479"}, {"drawNumber":"51117478"}, {"drawNumber":"51117477"}, {"drawNumber":"51117476"}, {"drawNumber":"51117475"}, {"drawNumber":"51117474"}, {"drawNumber":"51117473"}, {"drawNumber":"51117472"}, {"drawNumber":"51117471"}, {"drawNumber":"51117470"} ] gjson.Parse(str).ForEach(func(key, value gjson.Result) bool { fmt.Println("key", key.Int()) fmt.Println("key", value.Get("drawNumber").Int()) return true }) }

tidwall commented 5 months ago

The ForEach function loops over each entry in a JSON Object or Array. The key for an Object is the actual JSON key. For an Array it's the index of the value in the array.

For example:

package main

import (
    "fmt"

    "github.com/tidwall/gjson"
)

func main() {
    str := `[
      {"drawNumber": "51117487"},
      {"drawNumber": "51117486"},
      {"drawNumber": "51117485"},
      {"drawNumber": "51117484"},
      {"drawNumber": "51117483"},
      {"drawNumber": "51117482"}
    ]`
    gjson.Parse(str).ForEach(func(key, value gjson.Result) bool {
        fmt.Println("key", key.Int())
        fmt.Println("key", value.Get("drawNumber").Int())
        return true
    })
}
key 0
key 51117487
key 1
key 51117486
key 2
key 51117485
key 3
key 51117484
key 4
key 51117483
key 5
key 51117482

https://go.dev/play/p/VZBrsvyWMfY

vaecou commented 5 months ago

ForEach 函数循环遍历 JSON 对象或数组中的每个条目。 key for an Object 是实际的 JSON 键。对于数组,它是数组中值的索引。

 例如:

package main

import (
  "fmt"

  "github.com/tidwall/gjson"
)

func main() {
  str := `[
    {"drawNumber": "51117487"},
    {"drawNumber": "51117486"},
    {"drawNumber": "51117485"},
    {"drawNumber": "51117484"},
    {"drawNumber": "51117483"},
    {"drawNumber": "51117482"}
  ]`
  gjson.Parse(str).ForEach(func(key, value gjson.Result) bool {
      fmt.Println("key", key.Int())
      fmt.Println("key", value.Get("drawNumber").Int())
      return true
  })
}
key 0
key 51117487
key 1
key 51117486
key 2
key 51117485
key 3
key 51117484
key 4
key 51117483
key 5
key 51117482

https://go.dev/play/p/VZBrsvyWMfY

Very strange, I copied your code snippet for testing, but the result is still 0

image

vaecou commented 5 months ago

image

My current method is solved by self-increment. I don't know if this will cause any other problems, such as inaccurate sorting.