Skip to content

fix panic for empty jsonpaths #6

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

Merged
merged 1 commit into from
Feb 27, 2024
Merged
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
3 changes: 3 additions & 0 deletions jsonpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ func Compile(jpath string) (*Compiled, error) {
if err != nil {
return nil, err
}
if len(tokens) == 0 {
return nil, fmt.Errorf("empty path")
}
if tokens[0] != "@" && tokens[0] != "$" {
return nil, fmt.Errorf("$ or @ should in front of path")
}
Expand Down
10 changes: 8 additions & 2 deletions jsonpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,14 @@ func init() {
}

func Test_jsonpath_JsonPathLookup_1(t *testing.T) {
// empty string
res, err := JsonPathLookup(json_data, "")
if err == nil {
t.Errorf("expected error from empty jsonpath")
}

// key from root
res, _ := JsonPathLookup(json_data, "$.expensive")
res, _ = JsonPathLookup(json_data, "$.expensive")
if res_v, ok := res.(float64); ok != true || res_v != 10.0 {
t.Errorf("expensive should be 10")
}
Expand All @@ -89,7 +95,7 @@ func Test_jsonpath_JsonPathLookup_1(t *testing.T) {
}

// multiple index
res, err := JsonPathLookup(json_data, "$.store.book[0,1].price")
res, err = JsonPathLookup(json_data, "$.store.book[0,1].price")
t.Log(err, res)
if res_v, ok := res.([]interface{}); ok != true || res_v[0].(float64) != 8.95 || res_v[1].(float64) != 12.99 {
t.Errorf("exp: [8.95, 12.99], got: %v", res)
Expand Down