如何在JSON中找到节点

时间:2015-02-12 13:52:22

标签: json jsonpath

我有以下JSON

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

我想检查" notificationFormat"元素使用JSONPath表达式退出。我可以使用以下JSONPath表达式获取上面元素的值。

$.subscription.notificationFormat

我可以使用类似的表达式返回布尔值,检查元素是否存在吗?

3 个答案:

答案 0 :(得分:5)

如果我理解你的问题是正确的,这是一个答案。

这将检查你的json中是否存在notificationFormat。

$.subscription[?(@.notificationFormat)]

如果notificationFormat存在,那将获得所有destinationAddress

$.subscription[?(@.notificationFormat)].destinationAddress

答案 1 :(得分:0)

如果您正在使用Jayway的JSONPath Java实现 - JsonPath library - 并提前解析JSON一次,以使多次读取更有效,那么可以说比使用JSONPath过滤器更清晰表示)检查是否存在可选JSON属性的方法。使用已解析的JSON的ReadContext对象表示形式将父JSON对象作为Java HashMap返回,然后检查是否存在具有属性名称的映射条目。使用问题中的JSON,检查可选的'notificationFormat'属性是否存在的(Java)代码将是 -

ReadContext parsedJson = JsonPath.parse(jsonString);
HashMap subscription = parsedJson.read("$.subscription"); 
if (subscription.containsKey("notificationFormat")) {  
  ... 
}

答案 2 :(得分:-1)

Object result = JsonPath.parse("{}", com.jayway.jsonpath.Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS)).read("$.plugin.writer.mysqlwriter.path");
System.out.println("json exist");
相关问题