From e30a9c1037e0f9fbde93a6a9848a2dd5c59d3b91 Mon Sep 17 00:00:00 2001 From: Josh Baker Date: Tue, 18 Apr 2017 09:28:51 -0700 Subject: [PATCH] Default String() to empty when nonexistent or null This commit alters the behavior of string handling. Prior to this change, calling result.String() for nonexistent and null JSON members would return "null". This runs counter to the zero and omitempty defaults of Go. Thus I've been seeing in the wild: s := result.String() if s == "null" || s == "" { // ... handle empty string condition } Now we can simply write: if result.String() == "" { // ... handle empty string condition } It's still possible to explicitly check for null and existence. result.Type == gjson.Null result.Exists() --- gjson.go | 2 +- gjson_test.go | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gjson.go b/gjson.go index 52c37f4..82bd957 100644 --- a/gjson.go +++ b/gjson.go @@ -68,7 +68,7 @@ type Result struct { func (t Result) String() string { switch t.Type { default: - return "null" + return "" case False: return "false" case Number: diff --git a/gjson_test.go b/gjson_test.go index d4bbb1e..137974f 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -422,8 +422,8 @@ func TestBasic4(t *testing.T) { } _ = token.Value().(string) token = get(basicJSON, "name.last") - if token.String() != "null" { - t.Fatal("expecting 'null'", "got", token.String()) + if token.String() != "" { + t.Fatal("expecting ''", "got", token.String()) } if token.Value() != nil { t.Fatal("should be nil") @@ -683,6 +683,7 @@ func TestManyBasic(t *testing.T) { t.Fatalf("expected %v, got %v", len(paths), len(results)) } if fmt.Sprintf("%v", results) != expect { + fmt.Printf("%v\n", paths) t.Fatalf("expected %v, got %v", expect, results) } //if testLastWasFallback != shouldFallback { @@ -693,7 +694,7 @@ func TestManyBasic(t *testing.T) { testMany(false, `[emptya ["world peace"] 31]`, ".a", "loves", "age") testMany(false, `[["world peace"]]`, "loves") testMany(false, `[{"last":"Anderson","first":"Nancy"} Nancy]`, "name", "name.first") - testMany(true, `[null]`, strings.Repeat("a.", 40)+"hello") + testMany(true, `[]`, strings.Repeat("a.", 40)+"hello") res := Get(manyJSON, strings.Repeat("a.", 48)+"a") testMany(true, `[`+res.String()+`]`, strings.Repeat("a.", 48)+"a") // these should fallback