From 7db3b02e3f802ec019d7c85ed0b09f016e18a3e7 Mon Sep 17 00:00:00 2001 From: deef Date: Sat, 30 May 2020 06:16:06 -0400 Subject: [PATCH 1/2] update Result.Bool to use golang bool parsing golang has several tools that already parse boolean values in the standard library. Specifically strconv.ParseBool(string) https://golang.org/pkg/strconv/#ParseBool "ParseBool returns the boolean value represented by the string. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error." This change returns any matching ParseBool string to that boolean value, or if the string is not one of those values, the error being thrown, returns a false. --- gjson.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gjson.go b/gjson.go index 0b6dcb0..6c80729 100644 --- a/gjson.go +++ b/gjson.go @@ -106,7 +106,8 @@ func (t Result) Bool() bool { case True: return true case String: - return t.Str != "" && t.Str != "0" && t.Str != "false" + b, err := strconv.ParseBool(t.Str) + return !(!b || err != nil) case Number: return t.Num != 0 } From 78a59792a31da33afa7ad2cb20fe14851e6214b2 Mon Sep 17 00:00:00 2001 From: Jeffrey Koehler Date: Sat, 30 May 2020 06:34:47 -0400 Subject: [PATCH 2/2] add test of different strings Added test for each of the different accepted values for ParseBool, and a few arbitrary results that should return false. --- gjson_test.go | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/gjson_test.go b/gjson_test.go index 36a4273..eba498f 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -313,10 +313,25 @@ func TestTypes(t *testing.T) { assert(t, (Result{Type: JSON}).Type.String() == "JSON") assert(t, (Result{Type: 100}).Type.String() == "") // bool - assert(t, (Result{Type: String, Str: "true"}).Bool()) assert(t, (Result{Type: True}).Bool()) assert(t, (Result{Type: False}).Bool() == false) assert(t, (Result{Type: Number, Num: 1}).Bool()) + assert(t, (Result{Type: String, Str: "1"}).Bool()) + assert(t, (Result{Type: String, Str: "T"}).Bool()) + assert(t, (Result{Type: String, Str: "t"}).Bool()) + assert(t, (Result{Type: String, Str: "true"}).Bool()) + assert(t, (Result{Type: String, Str: "True"}).Bool()) + assert(t, (Result{Type: String, Str: "TRUE"}).Bool()) + assert(t, (Result{Type: String, Str: "tRuE"}).Bool() == false) + assert(t, (Result{Type: String, Str: "0"}).Bool() == false) + assert(t, (Result{Type: String, Str: "f"}).Bool() == false) + assert(t, (Result{Type: String, Str: "F"}).Bool() == false) + assert(t, (Result{Type: String, Str: "false"}).Bool() == false) + assert(t, (Result{Type: String, Str: "False"}).Bool() == false) + assert(t, (Result{Type: String, Str: "FALSE"}).Bool() == false) + assert(t, (Result{Type: String, Str: "fAlSe"}).Bool() == false) + assert(t, (Result{Type: String, Str: "random"}).Bool() == false) + // int assert(t, (Result{Type: String, Str: "1"}).Int() == 1) assert(t, (Result{Type: True}).Int() == 1)