Skip to content

Commit

Permalink
Set array index as key for ForEach
Browse files Browse the repository at this point in the history
See #248
  • Loading branch information
tidwall committed Dec 1, 2021
1 parent bd76212 commit db00337
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
10 changes: 7 additions & 3 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,17 +229,19 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
return
}
json := t.Raw
var keys bool
var obj bool
var i int
var key, value Result
for ; i < len(json); i++ {
if json[i] == '{' {
i++
key.Type = String
keys = true
obj = true
break
} else if json[i] == '[' {
i++
key.Type = Number
key.Num = -1
break
}
if json[i] > ' ' {
Expand All @@ -251,7 +253,7 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
var ok bool
var idx int
for ; i < len(json); i++ {
if keys {
if obj {
if json[i] != '"' {
continue
}
Expand All @@ -267,6 +269,8 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
}
key.Raw = str
key.Index = s + t.Index
} else {
key.Num += 1
}
for ; i < len(json); i++ {
if json[i] <= ' ' || json[i] == ',' || json[i] == ':' {
Expand Down
26 changes: 23 additions & 3 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,9 +435,9 @@ func TestBasic1(t *testing.T) {
mtok := get(basicJSON, `loggy.programmers`)
var count int
mtok.ForEach(func(key, value Result) bool {
if key.Exists() {
t.Fatalf("expected %v, got %v", false, key.Exists())
}
assert(t, key.Exists())
assert(t, key.String() == fmt.Sprint(count))
assert(t, key.Int() == int64(count))
count++
if count == 3 {
return false
Expand Down Expand Up @@ -2441,3 +2441,23 @@ func TestStaticJSON(t *testing.T) {
`[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)
}

0 comments on commit db00337

Please sign in to comment.