2

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"
}]
Akshay G
  • 2,070
  • 1
  • 15
  • 33
Infor.KS
  • 21
  • 1
  • 3

2 Answers2

2

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

Brank Victoria
  • 1,447
  • 10
  • 17
  • 1
    In my testing, the .. works, and its also documented here https://github.com/json-path/JsonPath#:~:text=books%20and%20bicycles-,%24.store..price,-The%20price%20of 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. – Infor.KS Mar 31 '22 at 14:05
  • You're totally right, I didn't know it, I will modify the answer, thank you – Brank Victoria Mar 31 '22 at 14:09
0

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]
Delta George
  • 2,560
  • 2
  • 17
  • 11