From 38c3f5c110e594830833993b88cffd2b3848acc3 Mon Sep 17 00:00:00 2001 From: Wei Fu Date: Mon, 18 Sep 2017 17:32:03 +0800 Subject: [PATCH] add IsNull helper method --- gjson.go | 9 +++++++++ gjson_test.go | 9 ++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/gjson.go b/gjson.go index f9fe002..e5a4ef5 100644 --- a/gjson.go +++ b/gjson.go @@ -571,6 +571,15 @@ func (t Result) Exists() bool { return t.Type != Null || len(t.Raw) != 0 } +// IsNull returns true if type is Null. +// +// if gjson.Get(json, "name.nullable").IsNull() { +// println("value is null") +// } +func (t Result) IsNull() bool { + return t.Type == Null +} + // Value returns one of these types: // // bool, for JSON booleans diff --git a/gjson_test.go b/gjson_test.go index 57f0425..c4ce3d8 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -136,7 +136,8 @@ var basicJSON = `{"age":100, "name":{"here":"B\\\"R"}, } ] }, - "lastly":{"yay":"final"} + "lastly":{"yay":"final"}, + "nullable": null }` var basicJSONB = []byte(basicJSON) @@ -240,6 +241,12 @@ func TestIsArrayIsObject(t *testing.T) { assert(t, !mtok.IsArray()) } +func TestIsNull(t *testing.T) { + value := get(basicJSON, "nullable") + assert(t, value.IsNull()) + assert(t, value.Exists()) +} + func TestPlus53BitInts(t *testing.T) { json := `{"IdentityData":{"GameInstanceId":634866135153775564}}` value := Get(json, "IdentityData.GameInstanceId")