Search code examples
jsonpath

extract ID from JSON filtering by value


I have the following JSON file

{
    "businessEventData": [
        {
            "businessEvent": {
                "header": {
                    "moduleName": "Reservation",
                    "primaryKey": "45901",
                    "createdDateTime": "2021-09-26 11:58:03.0"
                }
            }
        },
        {
            "businessEvent": {
                "header": {
                    "moduleName": "Reservation",
                    "primaryKey": "45901",
                    "createdDateTime": "2021-09-26 11:58:15.0"
                }
                
            }
            
        },
         {
            "businessEvent": {
                "header": {
                    "moduleName": "Profile",
                    "primaryKey": "45902",
                    "createdDateTime": "2021-09-25 11:58:03.0"
                }
            }
        }
    ]
}

I need to extract the primaryKey in the json object where the moduleName is equal to "Reservation". My desired output would be:

[
  "45901",
  "45901"
]

If I run the followig jsonPath $..header[?@.moduleName == "Reservation"].primaryKey I don't get any output.

As well, is there a way to get a unique list with jsonPath? Instead of:

[
  "45901",
  "45901"
]

to get

 [
   "45901"
 ]

Solution

  • What about:

    $.businessEventData[?(@.businessEvent.header.moduleName=='Reservation')]..header.primaryKey