Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

query values to see if they are truthy, in the JavaScript sense #318

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package gjson

import (
"math"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -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.
Expand Down
38 changes: 38 additions & 0 deletions gjson_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}