Set array index as key for ForEach

See #248
This commit is contained in:
tidwall 2021-11-30 17:20:07 -07:00
parent bd76212030
commit db0033701c
2 changed files with 30 additions and 6 deletions

View File

@ -229,17 +229,19 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
return return
} }
json := t.Raw json := t.Raw
var keys bool var obj bool
var i int var i int
var key, value Result var key, value Result
for ; i < len(json); i++ { for ; i < len(json); i++ {
if json[i] == '{' { if json[i] == '{' {
i++ i++
key.Type = String key.Type = String
keys = true obj = true
break break
} else if json[i] == '[' { } else if json[i] == '[' {
i++ i++
key.Type = Number
key.Num = -1
break break
} }
if json[i] > ' ' { if json[i] > ' ' {
@ -251,7 +253,7 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
var ok bool var ok bool
var idx int var idx int
for ; i < len(json); i++ { for ; i < len(json); i++ {
if keys { if obj {
if json[i] != '"' { if json[i] != '"' {
continue continue
} }
@ -267,6 +269,8 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
} }
key.Raw = str key.Raw = str
key.Index = s + t.Index key.Index = s + t.Index
} else {
key.Num += 1
} }
for ; i < len(json); i++ { for ; i < len(json); i++ {
if json[i] <= ' ' || json[i] == ',' || json[i] == ':' { if json[i] <= ' ' || json[i] == ',' || json[i] == ':' {

View File

@ -435,9 +435,9 @@ func TestBasic1(t *testing.T) {
mtok := get(basicJSON, `loggy.programmers`) mtok := get(basicJSON, `loggy.programmers`)
var count int var count int
mtok.ForEach(func(key, value Result) bool { mtok.ForEach(func(key, value Result) bool {
if key.Exists() { assert(t, key.Exists())
t.Fatalf("expected %v, got %v", false, key.Exists()) assert(t, key.String() == fmt.Sprint(count))
} assert(t, key.Int() == int64(count))
count++ count++
if count == 3 { if count == 3 {
return false return false
@ -2441,3 +2441,23 @@ func TestStaticJSON(t *testing.T) {
`[true,false,null,inf,nan,{"name":"andy","last":"Anderson"},["any","thing"]]`, `[true,false,null,inf,nan,{"name":"andy","last":"Anderson"},["any","thing"]]`,
) )
} }
func TestArrayKeys(t *testing.T) {
N := 100
json := "["
for i := 0; i < N; i++ {
if i > 0 {
json += ","
}
json += fmt.Sprint(i)
}
json += "]"
var i int
Parse(json).ForEach(func(key, value Result) bool {
assert(t, key.String() == fmt.Sprint(i))
assert(t, key.Int() == int64(i))
i++
return true
})
assert(t, i == N)
}