Skip to content

Commit 1ddbb34

Browse files
author
rhtang
committed
bugfix: get key from null
1 parent bd681f3 commit 1ddbb34

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

jsonpath.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"errors"
1313
)
1414

15+
var ErrGetFromNullObj = errors.New("get attribute from null object")
16+
1517
func JsonPathLookup(obj interface{}, jpath string) (interface{}, error) {
1618
steps, err := tokenize(jpath)
1719
//fmt.Println("f: steps: ", steps, err)
@@ -276,6 +278,9 @@ func filter_get_from_explicit_path(obj interface{}, path string) (interface{}, e
276278
}
277279

278280
func get_key(obj interface{}, key string) (interface{}, error) {
281+
if reflect.TypeOf(obj) == nil {
282+
return nil, ErrGetFromNullObj
283+
}
279284
switch reflect.TypeOf(obj).Kind() {
280285
case reflect.Map:
281286
for _, kv := range reflect.ValueOf(obj).MapKeys() {

jsonpath_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,3 +943,17 @@ func Test_jsonpath_string_equal(t *testing.T) {
943943
t.Fatalf("not the same: %v", res)
944944
}
945945
}
946+
947+
func Test_jsonpath_null_in_the_middle(t *testing.T) {
948+
data := `{
949+
"head_commit": null,
950+
}
951+
`
952+
953+
var j interface{}
954+
955+
json.Unmarshal([]byte(data), &j)
956+
957+
res, err := JsonPathLookup(j, "$.head_commit.author.username")
958+
t.Log(res, err)
959+
}

0 commit comments

Comments
 (0)