IsaacLevon
IsaacLevon

Reputation: 2580

JsonPath: find an element in an array by field

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"}
]

Upvotes: 1

Views: 3186

Answers (3)

Wilfred Clement
Wilfred Clement

Reputation: 2774

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'}")

Upvotes: 3

javaHolic
javaHolic

Reputation: 45

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

Upvotes: 0

Rony Nguyen
Rony Nguyen

Reputation: 1144

You may need

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

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

The name depends on when you extract your response

Upvotes: 0

Related Questions