json-path / JsonPath

Java JsonPath implementation
Apache License 2.0
8.86k stars 1.64k forks source link

Filter Nested Array and get only the first element #806

Open L1ncx opened 2 years ago

L1ncx commented 2 years ago

Im trying to filter the nested array (associatedClassification) of this JSON array to return only the first element it will find.

{ "elements": [ { "urn": "urn:li:lyndaCourse:189800", "details": { "classifications": [ { "associatedClassification": { "urn": "urn:li:lyndaCategory:9331", "type": "LIBRARY" } }, { "associatedClassification": { "urn": "urn:li:lyndaCategory:8982", "type": "SUBJECT" } }, { "associatedClassification": { "urn": "urn:li:lyndaCategory:8920", "type": "LIBRARY" } } ], } } ] }

I tried this JSONPATH query in https://jsonpath.herokuapp.com/

$.elements[0].details.classifications..associatedClassification[?(@.type=='LIBRARY')][0]

Expecting to get:

[ { "urn" : "urn:li:lyndaCategory:9331", "type" : "LIBRARY" } ]

But i actually get EMPTY array []

BugMaker-Boyan commented 2 years ago

Hi, I think the key point is about the execution order:

In your view: $.elements[0].details.classifications..associatedClassification[?(@.type=='LIBRARY')] will return [{"urn":"urn:li:lyndaCategory:9331","type":"LIBRARY"},{"urn":"urn:li:lyndaCategory:8920","type":"LIBRARY"}], then you use [0] to get the first element in the result array.

But in practice: ..associatedClassification[?(@.type=='LIBRARY')][0] means to find all the associatedClassification whose type is 'LIBRARY', and query the index 0's element of associatedClassification. However, associatedClassification is not a array, so index operator [] will not work well.

L1ncx commented 2 years ago

@BugMaker-Boyan But even if i modify the query to

$.elements[0].details.classifications[?(@.associatedClassification.type=='LIBRARY')][0] It still returngs empty []. From my understanding classifications is an array.

WLS2002 commented 2 years ago

@BugMaker-Boyan But even if i modify the query to

$.elements[0].details.classifications[?(@.associatedClassification.type=='LIBRARY')][0] It still returngs empty []. From my understanding classifications is an array.

Hi, I post a pull request and hope this can solve your problem:-)