From f528b28938d545e8e8fbe67a0738fcfb5f29e933 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 13 Sep 2020 10:44:11 +1000 Subject: [PATCH] Convert to JSON now handles non string keys --- cmd/read_test.go | 22 ++++++++++++++++++++++ pkg/yqlib/encoder.go | 17 +++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/cmd/read_test.go b/cmd/read_test.go index 64f89a30..2dd436b9 100644 --- a/cmd/read_test.go +++ b/cmd/read_test.go @@ -94,6 +94,28 @@ func TestReadUnwrapJsonByDefaultCmd(t *testing.T) { test.AssertResult(t, "\"frog\"\n", result.Output) } +func TestReadOutputJsonNonStringKeysCmd(t *testing.T) { + + content := ` +true: true +5: + null: + 0.1: deeply + false: things` + filename := test.WriteTempYamlFile(content) + defer test.RemoveTempYamlFile(filename) + + cmd := getRootCommand() + result := test.RunCmd(cmd, fmt.Sprintf("read %s -j", filename)) + + if result.Error != nil { + t.Error(result.Error) + } + expectedOutput := `{"5":{"null":{"0.1":"deeply","false":"things"}},"true":true} +` + test.AssertResult(t, expectedOutput, result.Output) +} + func TestReadWithAdvancedFilterCmd(t *testing.T) { cmd := getRootCommand() result := test.RunCmd(cmd, "read ../examples/sample.yaml b.e(name==sam).value") diff --git a/pkg/yqlib/encoder.go b/pkg/yqlib/encoder.go index 172fa389..fbacb963 100644 --- a/pkg/yqlib/encoder.go +++ b/pkg/yqlib/encoder.go @@ -58,6 +58,21 @@ type jsonEncoder struct { encoder *json.Encoder } +func mapKeysToStrings(node *yaml.Node) { + + if node.Kind == yaml.MappingNode { + for index, child := range node.Content { + if index % 2 == 0 { // its a map key + child.Tag = "!!str" + } + } + } + + for _, child := range node.Content { + mapKeysToStrings(child) + } +} + func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder { var encoder = json.NewEncoder(destination) var indentString = "" @@ -73,6 +88,8 @@ func NewJsonEncoder(destination io.Writer, prettyPrint bool, indent int) Encoder func (je *jsonEncoder) Encode(node *yaml.Node) error { var dataBucket interface{} + // firstly, convert all map keys to strings + mapKeysToStrings(node) errorDecoding := node.Decode(&dataBucket) if errorDecoding != nil { return errorDecoding