From 08fc058934c48bf57b55063fe59af726d382b6d3 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sat, 30 Oct 2021 13:37:21 +1100 Subject: [PATCH] Fix JSON encoding removing null #985 --- pkg/yqlib/encoder.go | 3 ++- pkg/yqlib/encoder_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/yqlib/encoder.go b/pkg/yqlib/encoder.go index a77b57cb..2e92e3aa 100644 --- a/pkg/yqlib/encoder.go +++ b/pkg/yqlib/encoder.go @@ -211,7 +211,8 @@ func (o *orderedMap) UnmarshalYAML(node *yaml.Node) error { } return nil case yaml.SequenceNode: - var res []orderedMap + // note that this has to be a pointer, so that nulls can be represented. + var res []*orderedMap if err := node.Decode(&res); err != nil { return err } diff --git a/pkg/yqlib/encoder_test.go b/pkg/yqlib/encoder_test.go index 333749d9..283e89ee 100644 --- a/pkg/yqlib/encoder_test.go +++ b/pkg/yqlib/encoder_test.go @@ -48,6 +48,24 @@ banana: test.AssertResult(t, expectedJson, actualJson) } +func TestJsonNullInArray(t *testing.T) { + var sampleYaml = `[null]` + var actualJson = yamlToJson(sampleYaml, 0) + test.AssertResult(t, sampleYaml, actualJson) +} + +func TestJsonNull(t *testing.T) { + var sampleYaml = `null` + var actualJson = yamlToJson(sampleYaml, 0) + test.AssertResult(t, sampleYaml, actualJson) +} + +func TestJsonNullInObject(t *testing.T) { + var sampleYaml = `{x: null}` + var actualJson = yamlToJson(sampleYaml, 0) + test.AssertResult(t, `{"x":null}`, actualJson) +} + func TestJsonEncoderDoesNotEscapeHTMLChars(t *testing.T) { var sampleYaml = `build: "( ./lint && ./format && ./compile ) < src.code"` var expectedJson = `{"build":"( ./lint && ./format && ./compile ) < src.code"}`