How to get JSONPath to return property of parent of matched element

1.3k views Asked by At

I have a JSONPath expression that is matching the expected node. But I want to return a property of the parent of that node.

Here is the source json:

{
  "totalRecords": 2,
  "totalRecordsSpecified": true,
  "recordList": [
      {
      "name": "34-34",
      "customFieldList": [
        {
          "value": {
            "name": "PANTS",
            "internalId": "46",
            "typeId": "91"
          },
          "internalId": "933",
          "scriptId": "custrecord_size_range",
          "_typeName": "SelectCustomFieldRef"
        }
      ],
      "internalId": "343",
      "_typeName": "CustomRecord"
    },
    {
      "name": "34-34",
      "customFieldList": [
        {
          "value": {
            "name": "JEANS",
            "internalId": "44",
            "typeId": "91"
          },
          "internalId": "933",
          "scriptId": "custrecord_size_range",
          "_typeName": "SelectCustomFieldRef"
        }
      ],
      "internalId": "321",
      "_typeName": "CustomRecord"
    }
  ]
}

Here is the JSONPath Expression: $.recordList[.customFieldList[?(@.value.name=='JEANS')]]

and it returns the following match:

[
  {
    "value": {
      "name": "JEANS",
      "internalId": "44",
      "typeId": "91"
    },
    "internalId": "933",
    "scriptId": "custrecord_size_range",
    "_typeName": "SelectCustomFieldRef"
  }
]

However, what I want to return is the .internalId property of the PARENT element that contains the customFieldList array from which the above element got matched.

Perhaps by way of screenshot: JSONPath Evaluator

How do I need to change my JSONPath Expression to return the indicated parent property?

1

There are 1 answers

1
wp78de On

Formulating the correct syntax to get the expected result comes down to the implementation details of the applied JSONPath library. It looks like you are using the JsonPath-Plus library (since you use this specific online tester). JsonPath-Plus allows us to use the ^ parent-node operator to go one level up, i.e. using your path we could do something like this:

$.recordList[.customFieldList[?(@.value.name=='JEANS')]]^^^.internalId

We can formulate a very straight-forward path that works with the Gatling implementation (and probably some other libraries) like this:

$.recordList[?(@.customFieldList[*].value.name=='JEANS')].internalId

I even found a path that works with Goessner's basic JavaScript JsonPath implementation (It's a bit dubious why index 0 yields the correct result; this probably does not work with multiple results and should be treated with caution)

$.recordList[?(@.customFieldList[0].value.name=='JEANS')].internalId

You can test this path here using various JSONPath implementations (you can switch between tabs, then click Go). As you can see, this very much depends on the underlying library your environment or tool is using.