5

Im trying to filter the elements 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"
                    }
                }
            ]
        }
    }]
}

But this results in an EMPTY array [].

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

2 Answers 2

4

The following works on all elements:

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

and returns a list of all matching associatedClassification objects.

JSONPath is expected to point inside the original document. Therefore, getting the first element from the result list would require post-processing, e.g. a separate JSONPath, e.g.

$.[0]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! It took me a lot to find this solution.
naively, I find this ridiculous, but thank you for confirming.
3

Another way to filter the information is by filtering the property "classification" (without using ".."), and use "associatedClassification.type" in your filter, so you should have something like this:

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

With the above JSONPATH you will have all items which type is "LIBRARY" (in your example will return 2 items).

You mentioned you need only the first one of the filtered items, as far as I investigated it seems there's no posible solution to return only the first item using only JSONPATH (see the thread bellow):

https://github.com/json-path/JsonPath/issues/272

2 Comments

In my testing, the .. works, and its also documented here github.com/json-path/… anyway - my main problem is getting the first item of the result set and yeah it looks like it can't be done just by jsonpath.
You're totally right, I didn't know it, I will modify the answer, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.