From 26effddb8c01d926f0fc18bc85f0e2b79b64eecc Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Thu, 23 Nov 2023 11:53:18 +1100 Subject: [PATCH] Fixed empty array json bug #1880 --- pkg/yqlib/candidiate_node_json.go | 9 +++++++-- pkg/yqlib/json_test.go | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/pkg/yqlib/candidiate_node_json.go b/pkg/yqlib/candidiate_node_json.go index 728e5afb7b..fe7d344ee8 100644 --- a/pkg/yqlib/candidiate_node_json.go +++ b/pkg/yqlib/candidiate_node_json.go @@ -162,8 +162,13 @@ func (o *CandidateNode) MarshalJSON() ([]byte, error) { buf.WriteByte('}') return buf.Bytes(), nil case SequenceNode: - log.Debugf("MarshalJSON SequenceNode") - err := enc.Encode(o.Content) + log.Debugf("MarshalJSON SequenceNode, %v, len: %v", o.Content, len(o.Content)) + var err error + if len(o.Content) == 0 { + buf.WriteString("[]") + } else { + err = enc.Encode(o.Content) + } return buf.Bytes(), err default: err := enc.Encode(nil) diff --git a/pkg/yqlib/json_test.go b/pkg/yqlib/json_test.go index ab0c7225b1..b36d1e19a0 100644 --- a/pkg/yqlib/json_test.go +++ b/pkg/yqlib/json_test.go @@ -80,6 +80,27 @@ const roundTripMultiLineJson = `{ ` var jsonScenarios = []formatScenario{ + { + description: "array empty", + skipDoc: true, + input: "[]", + scenarioType: "roundtrip-ndjson", + expected: "[]\n", + }, + { + description: "array has scalar", + skipDoc: true, + input: "[3]", + scenarioType: "roundtrip-ndjson", + expected: "[3]\n", + }, + { + description: "array has object", + skipDoc: true, + input: `[{"x": 3}]`, + scenarioType: "roundtrip-ndjson", + expected: "[{\"x\":3}]\n", + }, { description: "array null", skipDoc: true,