Katie
Katie

Reputation: 907

JSONPath filter with regex returns all values in the array rather than a subset

I am trying to figure out how to write a JSONPath filter that will select members of an array whose property ends in a substring. I'm trying it out with this tool.

The sample data the site gives you is

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

I expected a this filter to only give me the phone number of type "iPhone".

$.phoneNumbers[?(@.type =~ /ne$/ )]

Instead it gives me both phone numbers. Can anyone tell me why?

Upvotes: 2

Views: 3547

Answers (2)

Ashoob
Ashoob

Reputation: 11

Katie- sorry for delayed answer.

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

Hope will work this solution.

maybe this solution will useful to others.

Upvotes: 1

Daniel
Daniel

Reputation: 753

I believe the expression should match the whole string, otherwise you shouldn't get any results back.

This filter should work

$.phoneNumbers[?(@.type =~ /^[a-z|A-Z|0-9]+ne$/ )]

It works with jayway, jayway returns

[
  {
    "type" : "iPhone",
    "number" : "0123-4567-8888"
  }
]

But not, apparently, with Goessner.

I think jayway is right. My own C++ JsonPath implementation gives the same result as jayway.

Upvotes: 1

Related Questions