Open vaecou opened 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
该
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
Very strange, I copied your code snippet for testing, but the result is still 0
My current method is solved by self-increment. I don't know if this will cause any other problems, such as inaccurate sorting.
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 }) }