javajsonpathjayway

Get Parent Node using Jayway JSONPATH


In the below JSON file I want to extract the empDetails.name where one or both iscomponentInSal is true .

JSON

[
*// Retrieve below `empDetails.name` as for one of the components we have `"iscomponentInSal": true`* 
  {
    "empDetails": {
    "name":"John",
      "compensation": {
        "salary": [
          {
            "component": "Basic",
            "iscomponentInSal": true
          },
          {
            "component": "HRA",
            "iscomponentInSal": false
          }
        ]
      }
    }
  },
*// Do not retrieve below `empDetails.name` as for both components we have `"iscomponentInSal": false`* 
{
    "empDetails": {
    "name":"Steve",
      "compensation": {
        "salary": [
          {
            "component": "Basic",
            "iscomponentInSal": false
          },
          {
            "component": "HRA",
            "iscomponentInSal": false
          }
        ]
      }
    }
  }
]    

I tried few ways to extract the results as below , but was not successfull

$.[salary[?(@.iscomponentInSal == true)])]

//This retrieves below json

[
  {
    "component": "Basic",
    "iscomponentInSal": true
  }
]

Solution

  • There are different possible solutions using Jayway-JSONPath Filter Operators

    using nested expressions and empty filter operator.

    $[*].empDetails[?(@.compensation.salary[?(@.iscomponentInSal == true)] empty false)].name
    

    using in filter operator; right side expression returns an array

    $[*].empDetails[?(true in @.compensation.salary[*].iscomponentInSal)].name