Skip to content

Commit db00337

Browse files
committed
Set array index as key for ForEach
See #248
1 parent bd76212 commit db00337

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

gjson.go

+7-3
Original file line numberDiff line numberDiff line change
@@ -229,17 +229,19 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
229229
return
230230
}
231231
json := t.Raw
232-
var keys bool
232+
var obj bool
233233
var i int
234234
var key, value Result
235235
for ; i < len(json); i++ {
236236
if json[i] == '{' {
237237
i++
238238
key.Type = String
239-
keys = true
239+
obj = true
240240
break
241241
} else if json[i] == '[' {
242242
i++
243+
key.Type = Number
244+
key.Num = -1
243245
break
244246
}
245247
if json[i] > ' ' {
@@ -251,7 +253,7 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
251253
var ok bool
252254
var idx int
253255
for ; i < len(json); i++ {
254-
if keys {
256+
if obj {
255257
if json[i] != '"' {
256258
continue
257259
}
@@ -267,6 +269,8 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
267269
}
268270
key.Raw = str
269271
key.Index = s + t.Index
272+
} else {
273+
key.Num += 1
270274
}
271275
for ; i < len(json); i++ {
272276
if json[i] <= ' ' || json[i] == ',' || json[i] == ':' {

gjson_test.go

+23-3
Original file line numberDiff line numberDiff line change
@@ -435,9 +435,9 @@ func TestBasic1(t *testing.T) {
435435
mtok := get(basicJSON, `loggy.programmers`)
436436
var count int
437437
mtok.ForEach(func(key, value Result) bool {
438-
if key.Exists() {
439-
t.Fatalf("expected %v, got %v", false, key.Exists())
440-
}
438+
assert(t, key.Exists())
439+
assert(t, key.String() == fmt.Sprint(count))
440+
assert(t, key.Int() == int64(count))
441441
count++
442442
if count == 3 {
443443
return false
@@ -2441,3 +2441,23 @@ func TestStaticJSON(t *testing.T) {
24412441
`[true,false,null,inf,nan,{"name":"andy","last":"Anderson"},["any","thing"]]`,
24422442
)
24432443
}
2444+
2445+
func TestArrayKeys(t *testing.T) {
2446+
N := 100
2447+
json := "["
2448+
for i := 0; i < N; i++ {
2449+
if i > 0 {
2450+
json += ","
2451+
}
2452+
json += fmt.Sprint(i)
2453+
}
2454+
json += "]"
2455+
var i int
2456+
Parse(json).ForEach(func(key, value Result) bool {
2457+
assert(t, key.String() == fmt.Sprint(i))
2458+
assert(t, key.Int() == int64(i))
2459+
i++
2460+
return true
2461+
})
2462+
assert(t, i == N)
2463+
}

0 commit comments

Comments
 (0)