From 88bee2809f85a8697d18800974b42af4daa070b6 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Fri, 11 Jun 2021 14:27:44 +1000 Subject: [PATCH] Fixed issue on creating objects using [] --- pkg/yqlib/operator_equals_test.go | 4 ++-- pkg/yqlib/operator_traverse_path.go | 9 ++++++++- pkg/yqlib/operator_traverse_path_test.go | 7 +++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/pkg/yqlib/operator_equals_test.go b/pkg/yqlib/operator_equals_test.go index 6b7f2aa0..06fd7811 100644 --- a/pkg/yqlib/operator_equals_test.go +++ b/pkg/yqlib/operator_equals_test.go @@ -14,7 +14,7 @@ var equalsOperatorScenarios = []expressionScenario{ }, { skipDoc: true, - document: `a: cat`, + document: `a: cat`, expression: ".a == .b", expected: []string{ "D0, P[a], (!!bool)::false\n", @@ -22,7 +22,7 @@ var equalsOperatorScenarios = []expressionScenario{ }, { skipDoc: true, - document: `a: cat`, + document: `a: cat`, expression: ".b == .a", expected: []string{ "D0, P[a], (!!bool)::false\n", diff --git a/pkg/yqlib/operator_traverse_path.go b/pkg/yqlib/operator_traverse_path.go index 98ba5356..d87b0e20 100644 --- a/pkg/yqlib/operator_traverse_path.go +++ b/pkg/yqlib/operator_traverse_path.go @@ -127,9 +127,16 @@ func traverseArrayIndices(context Context, matchingNode *CandidateNode, indicesT node := matchingNode.Node if node.Tag == "!!null" { log.Debugf("OperatorArrayTraverse got a null - turning it into an empty array") - // auto vivification, make it into an empty array + // auto vivification node.Tag = "" node.Kind = yaml.SequenceNode + //check that the indices are numeric, if not, then we should create an object + if len(indicesToTraverse) != 0 { + _, err := strconv.ParseInt(indicesToTraverse[0].Value, 10, 64) + if err != nil { + node.Kind = yaml.MappingNode + } + } } if node.Kind == yaml.AliasNode { diff --git a/pkg/yqlib/operator_traverse_path_test.go b/pkg/yqlib/operator_traverse_path_test.go index dd917fd4..9e230915 100644 --- a/pkg/yqlib/operator_traverse_path_test.go +++ b/pkg/yqlib/operator_traverse_path_test.go @@ -43,6 +43,13 @@ var traversePathOperatorScenarios = []expressionScenario{ "D0, P[0 0 0], (!!int)::1\n", }, }, + { + skipDoc: true, + expression: `.["cat"] = "thing"`, + expected: []string{ + "D0, P[], ()::cat: thing\n", + }, + }, { description: "Simple map navigation", document: `{a: {b: apple}}`,