From 77477ee1e81e343d9d83a853c570c6df9301623c Mon Sep 17 00:00:00 2001 From: Chris Sokol Date: Wed, 15 Mar 2023 12:34:37 -0400 Subject: [PATCH] query values to see if they are truthy, in the JavaScript sense --- gjson.go | 17 +++++++++++++++++ gjson_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/gjson.go b/gjson.go index 53cbd23..82cd9bd 100644 --- a/gjson.go +++ b/gjson.go @@ -2,6 +2,7 @@ package gjson import ( + "math" "strconv" "strings" "time" @@ -187,6 +188,22 @@ func (t Result) Time() time.Time { return res } +// Truthy returns the truthiness of the value (all values are truthy except false, null, 0, -0, NaN, and ""). +func (t Result) Truthy() bool { + switch t.Type { + case Null, False: + return false + case Number: + return math.IsNaN(t.Num) == false && t.Num != 0 + case String: + return t.Str != "" + case True, JSON: + return true + default: + return false + } +} + // Array returns back an array of values. // If the result represents a null value or is non-existent, then an empty // array will be returned. diff --git a/gjson_test.go b/gjson_test.go index 77f6ce9..6511611 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -2591,3 +2591,41 @@ func TestIssue301(t *testing.T) { assert(t, Get(json, `fav\.movie.[1]`).String() == "[]") } + +func TestTruthy(t *testing.T) { + json := `{ + "aye1": true, + "aye2": 1, + "aye3": -1, + "aye4": 0.001, + "aye5": "aye", + "aye6": {}, + "aye7": [], + "aye8": +Inf, + "aye9": -Inf, + + "nay1": false, + "nay2": null, + "nay3": 0, + "nay4": -0, + "nay5": "", + "nay6": NaN, + }` + + assert(t, Get(json, "aye1").Truthy() == true) + assert(t, Get(json, "aye2").Truthy() == true) + assert(t, Get(json, "aye3").Truthy() == true) + assert(t, Get(json, "aye4").Truthy() == true) + assert(t, Get(json, "aye5").Truthy() == true) + assert(t, Get(json, "aye6").Truthy() == true) + assert(t, Get(json, "aye7").Truthy() == true) + assert(t, Get(json, "aye8").Truthy() == true) + assert(t, Get(json, "aye9").Truthy() == true) + + assert(t, Get(json, "nay1").Truthy() == false) + assert(t, Get(json, "nay2").Truthy() == false) + assert(t, Get(json, "nay3").Truthy() == false) + assert(t, Get(json, "nay4").Truthy() == false) + assert(t, Get(json, "nay5").Truthy() == false) + assert(t, Get(json, "nay6").Truthy() == false) +}