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()
This commit is contained in:
Josh Baker 2017-04-18 09:28:51 -07:00
parent 039b641eab
commit e30a9c1037
2 changed files with 5 additions and 4 deletions

View File

@ -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:

View File

@ -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