Skip to content

Commit

Permalink
The Array method should return back one item for JSON objects.
Browse files Browse the repository at this point in the history
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
  • Loading branch information
tidwall committed Oct 12, 2021
1 parent 77a57fd commit 4fe1916
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
7 changes: 4 additions & 3 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 4fe1916

Please sign in to comment.