diff --git a/gjson.go b/gjson.go index 1403506..90b4929 100644 --- a/gjson.go +++ b/gjson.go @@ -187,6 +187,16 @@ func (t Result) Array() []Result { return r.a } +// IsObject returns true if the result value is a JSON object. +func (t Result) IsObject() bool { + return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '{' +} + +// IsObject returns true if the result value is a JSON array. +func (t Result) IsArray() bool { + return t.Type == JSON && len(t.Raw) > 0 && t.Raw[0] == '[' +} + // ForEach iterates through values. // If the result represents a non-existent value, then no values will be iterated. // If the result is an Object, the iterator will pass the key and value of each item. diff --git a/gjson_test.go b/gjson_test.go index 48ade51..2949774 100644 --- a/gjson_test.go +++ b/gjson_test.go @@ -223,6 +223,23 @@ func TestBasic(t *testing.T) { } } +func TestIsArrayIsObject(t *testing.T) { + mtok := get(basicJSON, "loggy") + assert(t, mtok.IsObject()) + assert(t, !mtok.IsArray()) + + mtok = get(basicJSON, "loggy.programmers") + assert(t, !mtok.IsObject()) + assert(t, mtok.IsArray()) + + mtok = get(basicJSON, `loggy.programmers.#[tag="good"]#.firstName`) + assert(t, mtok.IsArray()) + + mtok = get(basicJSON, `loggy.programmers.0.firstName`) + assert(t, !mtok.IsObject()) + assert(t, !mtok.IsArray()) +} + func TestPlus53BitInts(t *testing.T) { json := `{"IdentityData":{"GameInstanceId":634866135153775564}}` value := Get(json, "IdentityData.GameInstanceId")