From 336cd89c1c76aaea9da1360f27d2fba68bd3ece1 Mon Sep 17 00:00:00 2001 From: nick Date: Thu, 6 Aug 2026 17:37:25 -0700 Subject: [PATCH] Handle null inputs in get_range --- jsonpath.go | 9 ++++++--- jsonpath_test.go | 31 +++++++++++++++++++++++++------ 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/jsonpath.go b/jsonpath.go index dc2b279..6325147 100644 --- a/jsonpath.go +++ b/jsonpath.go @@ -23,7 +23,6 @@ import ( var ErrGetFromNullObj = errors.New("get attribute from null object") var ErrKeyError = errKind.NewKind("key error: %s not found in object") - func JsonPathLookup(obj interface{}, jpath string) (interface{}, error) { c, err := Compile(jpath) if err != nil { @@ -264,7 +263,7 @@ func tokenize(query string) ([]string, error) { } /* - op: "root", "key", "idx", "range", "filter", "scan" +op: "root", "key", "idx", "range", "filter", "scan" */ func parse_token(token string) (op string, key string, args interface{}, err error) { if token == "$" { @@ -441,7 +440,11 @@ func get_idx(obj interface{}, idx int) (interface{}, error) { } func get_range(obj, frm, to interface{}) (interface{}, error) { - switch reflect.TypeOf(obj).Kind() { + typeOfObj := reflect.TypeOf(obj) + if typeOfObj == nil { + return nil, ErrGetFromNullObj + } + switch typeOfObj.Kind() { case reflect.Slice: length := reflect.ValueOf(obj).Len() _frm := 0 diff --git a/jsonpath_test.go b/jsonpath_test.go index f7c4a9a..8910e15 100644 --- a/jsonpath_test.go +++ b/jsonpath_test.go @@ -116,7 +116,7 @@ func Test_jsonpath_JsonPathLookup_1(t *testing.T) { if res_v, ok := res.([]interface{}); ok != true || res_v[0].(float64) != 8.95 || res_v[1].(float64) != 12.99 || res_v[2].(float64) != 8.99 || res_v[3].(float64) != 22.99 { t.Errorf("exp: [8.95, 12.99, 8.99, 22.99], got: %v", res) } - + // range res, err = JsonPathLookup(json_data, "$.store.book[0:1].price") t.Log(err, res) @@ -132,6 +132,25 @@ func Test_jsonpath_JsonPathLookup_1(t *testing.T) { t.Errorf("title are wrong: %v", res) } } + + // null input + res, err = JsonPathLookup(nil, "$.store") + if err == nil { + t.Errorf("expected error from nil json data") + } + + res, err = JsonPathLookup(nil, "$[*]") + if err == nil { + t.Errorf("expected error from nil json data") + } + + res, err = JsonPathLookup(nil, "$") + if err != nil { + t.Errorf("unexpected error for JsonPathLookup(nil, \"$\"): %s", err.Error()) + } + if res != nil { + t.Errorf("exp: nil, got: %v", res) + } } func Test_jsonpath_JsonPathLookup_filter(t *testing.T) { @@ -588,15 +607,15 @@ func Test_jsonpath_get_scan(t *testing.T) { } obj4 := map[string]interface{}{ - "key1" : "abc", - "key2" : 123, - "key3" : map[string]interface{}{ + "key1": "abc", + "key2": 123, + "key3": map[string]interface{}{ "a": 1, "b": 2, "c": 3, }, - "key4" : []interface{}{1,2,3}, - "key5" : nil, + "key4": []interface{}{1, 2, 3}, + "key5": nil, } res, err = get_scan(obj4) res_v, ok = res.([]interface{})