10

I have following JSON

{"subscription": 
 {
 "callbackReference": "xyz" ,
 "criteria": "Vote",
 "destinationAddress": "3456" ,
  "notificationFormat" : "JSON"
 }
}

I want to check whether "notificationFormat" elements exits there using JSONPath expression. I can get the value of above element using following JSONPath expression.

$.subscription.notificationFormat

Can I use similar kind of expression which returns boolean value checking whether elements exists ?

Malintha
  • 4,512
  • 9
  • 48
  • 82
  • That's not valid JSON. Check at http://jsonlint.com/ –  Feb 12 '15 at 13:56
  • OK. What does this JSONPath expression return for a missing property? What does it return for a `false` property? What for an empty string property? Maybe this could be enough to tell if the property exists. –  Feb 12 '15 at 14:07

3 Answers3

14

If I understood your question correct here is an answer.

This would check if notificationFormat exists in your json.

$.subscription[?(@.notificationFormat)]

That would get all destinationAddress in case if notificationFormat exists

$.subscription[?(@.notificationFormat)].destinationAddress
Dmytro Pastovenskyi
  • 5,240
  • 5
  • 37
  • 56
  • The key part of the above solution is the JSONPath filter expression syntax "[?@.]". You can test the expression by using an online JSONPath evaluator, such as the one provided by the Jayway JsonPath project at http://jsonpath.herokuapp.com/. If you're using Jayway's Java implementation of JSONPath - the JsonPath library - then there is also an alternative solution. See my answer below. – Neil Brown Dec 22 '17 at 13:07
  • @NeilBrown, I am curious is there a way of selecting nodes that **do not** contain specific subnode? – Gabrielius Nov 25 '22 at 17:18
1
    ReadContext ctx = JsonPath.parse("{}", com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS));

    assertThat(ctx.read("$.components"), nullValue());
pavel
  • 2,964
  • 2
  • 14
  • 14
zach ma
  • 21
  • 1
0

If you're using Jayway's Java implementation of JSONPath - the JsonPath library - and parsing the JSON once, ahead of time, to make multiple reads more efficient, then there is an arguably clearer (than using a JSONPath filter expression) way to check whether an optional JSON property exists. Use the ReadContext object representation of the parsed JSON to return the parent JSON object as a Java HashMap, then check whether a map entry exists with the property's name. Using the JSON from the question, the (Java) code to check whether the optional 'notificationFormat' property exists would be -

ReadContext parsedJson = JsonPath.parse(jsonString);
HashMap subscription = parsedJson.read("$.subscription"); 
if (subscription.containsKey("notificationFormat")) {  
  ... 
}
Neil Brown
  • 409
  • 5
  • 6