Skip to content

Commit 0d75edf

Browse files
mikefarahMike Farah
authored andcommitted
Fixed updating array bug (Issue 3 in git)
1 parent 037314a commit 0d75edf

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

data_navigator.go

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,25 @@ func write(context map[interface{}]interface{}, head string, tail []string, valu
99
if len(tail) == 0 {
1010
context[head] = value
1111
} else {
12-
// e.g. if updating a.b.c, we need to get the 'b' map...
13-
toUpdate := readMap(context, head, tail[0:len(tail)-1]).(map[interface{}]interface{})
14-
// and then set the 'c' key.
15-
key := (tail[len(tail)-1])
16-
toUpdate[key] = value
12+
// e.g. if updating a.b.c, we need to get the 'b', this could be a map or an array
13+
var parent = readMap(context, head, tail[0:len(tail)-1])
14+
switch parent.(type) {
15+
case map[interface{}]interface{}:
16+
toUpdate := parent.(map[interface{}]interface{})
17+
// b is a map, update the key 'c' to the supplied value
18+
key := (tail[len(tail)-1])
19+
toUpdate[key] = value
20+
case []interface{}:
21+
toUpdate := parent.([]interface{})
22+
// b is an array, update it at index 'c' to the supplied value
23+
rawIndex := (tail[len(tail)-1])
24+
index, err := strconv.ParseInt(rawIndex, 10, 64)
25+
if err != nil {
26+
die("Error accessing array: %v", err)
27+
}
28+
toUpdate[index] = value
29+
}
30+
1731
}
1832
}
1933

data_navigator_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,18 @@ b:
119119
assertResult(t, "4", b["c"].(string))
120120
}
121121

122+
func TestWrite_array(t *testing.T) {
123+
var data = parseData(`
124+
b:
125+
- aa
126+
`)
127+
128+
write(data, "b", []string{"0"}, "bb")
129+
130+
b := data["b"].([]interface{})
131+
assertResult(t, "bb", b[0].(string))
132+
}
133+
122134
func TestWrite_with_no_tail(t *testing.T) {
123135
var data = parseData(`
124136
b:

0 commit comments

Comments
 (0)