From 4fe1916c56fbd3e4ee981981a7cdad58a7522f4b Mon Sep 17 00:00:00 2001 From: tidwall Date: Tue, 12 Oct 2021 10:52:30 -0700 Subject: [PATCH] The Array method should return back one item for JSON objects. This commit fixes an issue where the Array method was not returning single value arrays when the reciever Result was a JSON Object. fixes #240 --- gjson.go | 7 ++++--- gjson_test.go | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/gjson.go b/gjson.go index 95d210b..0d42394 100644 --- a/gjson.go +++ b/gjson.go @@ -189,14 +189,15 @@ func (t Result) Time() time.Time { } // Array returns back an array of values. -// If the result represents a non-existent value, then an empty array will be -// returned. If the result is not a JSON array, the return value will be an +// If the result represents a null value or is non-existent, then an empty +// array will be returned. +// If the result is not a JSON array, the return value will be an // array containing one result. func (t Result) Array() []Result { if t.Type == Null { return []Result{} } - if t.Type != JSON { + if !t.IsArray() { return []Result{t} } r := t.arrayOrMap('[', false) diff --git a/gjson_test.go b/gjson_test.go index fb74d50..3c70a41 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -2189,3 +2189,21 @@ func TestIndexesMatchesRaw(t *testing.T) { assert(t, Parse(exampleJSON[r.Indexes[0]:]).Get("first").String() == "Dale") assert(t, Parse(exampleJSON[r.Indexes[1]:]).Get("first").String() == "Roger") } + +func TestIssue240(t *testing.T) { + nonArrayData := `{"jsonrpc":"2.0","method":"subscription","params": + {"channel":"funny_channel","data": + {"name":"Jason","company":"good_company","number":12345} + } + }` + parsed := Parse(nonArrayData) + assert(t, len(parsed.Get("params.data").Array()) == 1) + + arrayData := `{"jsonrpc":"2.0","method":"subscription","params": + {"channel":"funny_channel","data":[ + {"name":"Jason","company":"good_company","number":12345} + ]} + }` + parsed = Parse(arrayData) + assert(t, len(parsed.Get("params.data").Array()) == 1) +}