Improved handling of numeric keys

When there is no match at a given path, numeric keys are assumed to be strings.
To create an array '+' must be used.

e.g: yq n thing[+].cat fred
will create an array under thing, whereas
yq n thing[0].cat fred
will create a map under thing, with a key '0'
This commit is contained in:
Mike Farah 2019-05-16 10:01:34 +10:00
parent c7f5261036
commit 84de9c078d
4 changed files with 8 additions and 8 deletions

View File

@ -385,12 +385,11 @@ func TestPrefixCmdArray(t *testing.T) {
defer removeTempYamlFile(filename)
cmd := getRootCommand()
result := runCmd(cmd, fmt.Sprintf("prefix %s [0].d.[1]", filename))
result := runCmd(cmd, fmt.Sprintf("prefix %s [+].d.[+]", filename))
if result.Error != nil {
t.Error(result.Error)
}
expectedOutput := `- d:
- null
- b:
c: 3
`

View File

@ -89,14 +89,15 @@ func updatedChildValue(child interface{}, remainingPaths []string, value interfa
}
log.Debugf("updatedChildValue for child %v with path %v to set value %v", child, remainingPaths, value)
log.Debugf("type of child is %v", reflect.TypeOf(child))
_, nextIndexErr := strconv.ParseInt(remainingPaths[0], 10, 64)
arrayCommand := nextIndexErr == nil || remainingPaths[0] == "+" || remainingPaths[0] == "*"
switch child := child.(type) {
case nil:
if arrayCommand {
if remainingPaths[0] == "+" || remainingPaths[0] == "*" {
return writeArray(child, remainingPaths, value)
}
case []interface{}:
_, nextIndexErr := strconv.ParseInt(remainingPaths[0], 10, 64)
arrayCommand := nextIndexErr == nil || remainingPaths[0] == "+" || remainingPaths[0] == "*"
if arrayCommand {
return writeArray(child, remainingPaths, value)
}

View File

@ -260,7 +260,7 @@ a: apple
b:
- c: "4"`
updated := writeMap(data, []string{"b", "0", "c"}, "4")
updated := writeMap(data, []string{"b", "+", "c"}, "4")
got, _ := yamlToString(updated)
assertResult(t, expected, got)
}
@ -275,7 +275,7 @@ b:
d:
- "4"`
updated := writeMap(data, []string{"b", "d", "0"}, "4")
updated := writeMap(data, []string{"b", "d", "+"}, "4")
got, _ := yamlToString(updated)
assertResult(t, expected, got)
}

View File

@ -1,2 +1,2 @@
b.c: cat
b.e[0].name: Mike Farah
b.e[+].name: Mike Farah