Search code examples
jsonpath

How to match values in JsonPath


How do I match specific values in JSONPath?

Sample (from jsonpath.com):

{
  "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"
    }
  ]
}

How do I find:

  • The iPhone number
  • All numbers ending with 88

I tried:

$.phoneNumbers[?(@.type=~/iPhone/i)].number
$..number[?(@=~/.*88/i)]

Solution

  • For the numbers ending with 88 you should do:

    Option 1 (works in Jayway, not in Goessner):

    phoneNumbers[?(@.number =~ /^.*88$/i)].number
    

    Option 2 (works in Goessner, not in Jayway):

    phoneNumbers[?(/.*[88]$/.test(@.number))].number
    

    To find the iPhone number you should do:

    phoneNumbers[?(@.type=='iPhone')].number