Skip to content

Commit 0ea374a

Browse files
geseqEarncef Sequeira
andauthored
fix nested array access (#104)
Co-authored-by: Earncef Sequeira <[email protected]>
1 parent a5b1e6c commit 0ea374a

File tree

2 files changed

+42
-9
lines changed

2 files changed

+42
-9
lines changed

accessors.go

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,15 @@ func getKey(s string) (string, string) {
116116
func access(current interface{}, selector string, value interface{}, isSet bool) interface{} {
117117
thisSel, nextSel := getKey(selector)
118118

119-
index := -1
120-
if strings.Contains(thisSel, "[") {
119+
indexes := []int{}
120+
for strings.Contains(thisSel, "[") {
121+
prevSel := thisSel
122+
index := -1
121123
index, thisSel = getIndex(thisSel)
124+
indexes = append(indexes, index)
125+
if prevSel == thisSel {
126+
break
127+
}
122128
}
123129

124130
if curMap, ok := current.(Map); ok {
@@ -134,7 +140,7 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
134140
}
135141

136142
_, ok := curMSI[thisSel].(map[string]interface{})
137-
if (curMSI[thisSel] == nil || !ok) && index == -1 && isSet {
143+
if (curMSI[thisSel] == nil || !ok) && len(indexes) == 0 && isSet {
138144
curMSI[thisSel] = map[string]interface{}{}
139145
}
140146

@@ -144,15 +150,23 @@ func access(current interface{}, selector string, value interface{}, isSet bool)
144150
}
145151

146152
// do we need to access the item of an array?
147-
if index > -1 {
148-
if array, ok := interSlice(current); ok {
149-
if index < len(array) {
150-
current = array[index]
151-
} else {
152-
current = nil
153+
if len(indexes) > 0 {
154+
num := len(indexes)
155+
for num > 0 {
156+
num--
157+
index := indexes[num]
158+
indexes = indexes[:num]
159+
if array, ok := interSlice(current); ok {
160+
if index < len(array) {
161+
current = array[index]
162+
} else {
163+
current = nil
164+
break
165+
}
153166
}
154167
}
155168
}
169+
156170
if nextSel != "" {
157171
current = access(current, nextSel, value, isSet)
158172
}

accessors_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,22 @@ func TestAccessorsSet(t *testing.T) {
218218

219219
assert.Equal(t, "Mat", m.Get("name").Data())
220220
}
221+
222+
func TestAccessorsNested(t *testing.T) {
223+
d := objx.MustFromJSON(`{"values":[["test", "test1"], ["test2", {"name":"Mat"}, {"names": ["Captain", "Mat"]}]]}`)
224+
225+
value := d.Get("values[0][0]").String()
226+
assert.Equal(t, "test", value)
227+
228+
value = d.Get("values[0][1]").String()
229+
assert.Equal(t, "test1", value)
230+
231+
value = d.Get("values[1][0]").String()
232+
assert.Equal(t, "test2", value)
233+
234+
value = d.Get("values[1][1].name").String()
235+
assert.Equal(t, "Mat", value)
236+
237+
value = d.Get("values[1][2].names[0]").String()
238+
assert.Equal(t, "Captain", value)
239+
}

0 commit comments

Comments
 (0)