Search code examples
jsonpathjson-path-expression

Is there a way to return an attribute from a JSON object that is the result of a filtered expression?


If I have the following JSON I would like to know if it is possible to return the value "John" provided the following filter expression $[?(@.firstName="John")] is used to match the desired object.

{
  "firstName": "John",
  "lastName" : "doe",
  "age"      : 26,
  "address"  : {
    "streetAddress": "naist street",
    "city"         : "Nara",
    "postalCode"   : "630-0192"
  },
  "phoneNumbers": [
    {
      "type"  : "iPhone",
      "number": "0123-4567-8888"
    },
    {
      "type"  : "home",
      "number": "0123-4567-8910"
    }
  ]
}

In other words is it possible with a jsonpath expression to both have a conditional filter and return an attribute value from the matched json object. I have tried unsuccessfully creating such an expression using the JSONPath Online Evaluator at https://jsonpath.com/.


Solution

  • You can use, $.[?(@.firstName == 'John')].firstName. Remember, don't use https://jsonpath.com/ to evaluate your JSON paths. Instead use, http://jsonpath.herokuapp.com/..

    good luck..