JsonPath: find an element in an array by field

2.6k views Asked by At

I have an anonymous array of objects and I'd like to find an object by a specific field.

I tried this:

jsonPath.get("$.[?(@.name == 'David')]")

but I'm getting the following error:

Invalid JSON expression:
Script1.groovy: 1: Unexpected input: '                         $.[' @ line 1, column 29.
                            $.[?(@.name == 'David')]
                               ^

1 error

How do I fix that?

The json is:

[
 {"name": "David"}, {"name": "Ron"}, {"name": "Dana"}
]
3

There are 3 answers

2
Wilfred Clement On BEST ANSWER

The question is a bit ambiguous, But the syntax is incorrect, Json path syntax uses Groovy's GPath notation

js.getString("find {it.name == 'David'}")
2
Rony Nguyen On

You may need

$.[?(@.name == 'David')]

=>  $.data[?(@.name == 'David')]
    $.response[?(@.name == 'David')]
    $.body[?(@.name == 'David')]
    ...

The name depends on when you extract your response

2
javaHolic On

Because You are using json Array , do use - $[0] , since david is on first index.