sprad
sprad

Reputation: 343

JsonPath syntax for "does not include", or negative matching?

Consider this sample JSON:

{
  "thing": [
    {
      "name": "foo",
      "flag": "yep"
    },
    {
      "name": "bar"
    },
    {
      "name": "baz",
      "flag": "nope"
    }
  ]
}

If I wanted to find all the 'name' elements that DID have a corresponding 'flag', I could use something like this:

$.thing[?(@.flag)].name

I would get back the results:

'0' => "foo"
'1' => "baz"

But what if I wanted to find all the 'name' elements that DID NOT have a corresponding 'flag'?

(for the purposes of this question, I don't care about the value of 'flag', only whether or not it's present)

Upvotes: 8

Views: 7926

Answers (1)

sprad
sprad

Reputation: 343

I dug around in the JsonPath source code here (and specifically here) and found this test:

@Test
public void a_not_exists_filter_can_be_serialized() {

    String filter = filter(where("a").exists(false)).toString();
    String parsed = parse("[?(!@['a'])]").toString();

    assertThat(filter).isEqualTo(parsed);
}

So the syntax for doing the negative match I'm looking for would just be:

$.thing[?([email protected])].name

There's lots of other good examples in there. It'd be nice if they were in the documentation!

Upvotes: 10

Related Questions