From 182ad7605048a24cd37115b7157b8a4436d9ea17 Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Fri, 1 Dec 2017 14:13:24 -0700 Subject: [PATCH] Array() from null becomes zero length Go array fixes #53 --- gjson.go | 6 +++--- gjson_test.go | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/gjson.go b/gjson.go index e16a4b7..574432d 100644 --- a/gjson.go +++ b/gjson.go @@ -177,8 +177,8 @@ func (t Result) Time() time.Time { // 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 array containing one result. func (t Result) Array() []Result { - if !t.Exists() { - return nil + if t.Type == Null { + return []Result{} } if t.Type != JSON { return []Result{t} @@ -192,7 +192,7 @@ func (t Result) IsObject() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '{' } -// IsObject returns true if the result value is a JSON array. +// IsArray returns true if the result value is a JSON array. func (t Result) IsArray() bool { return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '[' } diff --git a/gjson_test.go b/gjson_test.go index 12cb244..283760a 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -1110,3 +1110,22 @@ func TestResultRawForLiteral(t *testing.T) { } } } + +func TestNullArray(t *testing.T) { + n := len(Get(`{"data":null}`, "data").Array()) + if n != 0 { + t.Fatalf("expected '%v', got '%v'", 0, n) + } + n = len(Get(`{}`, "data").Array()) + if n != 0 { + t.Fatalf("expected '%v', got '%v'", 0, n) + } + n = len(Get(`{"data":[]}`, "data").Array()) + if n != 0 { + t.Fatalf("expected '%v', got '%v'", 0, n) + } + n = len(Get(`{"data":[null]}`, "data").Array()) + if n != 1 { + t.Fatalf("expected '%v', got '%v'", 1, n) + } +}