Selecting a subset of JSON properties and values using JSONPath

我怕爱的太早我们不能终老 提交于 2020-08-07 20:00:06

问题


Given a JSON like:

{
  "a":1,
  "b":2,
  "c":3,
  "d":4,
  "e":5
}

How can I select out b, d and e to get the following JSON?

{
  "b":2,
  "d":4,
  "e":5
}

I want a JSON object and NOT only 2, 4 and 5 values?

This is what I'm trying with and failing:

$.[b,d,e]

回答1:


JSONPath is not suitable for what you are trying to achieve: JSONPath is designed to select values and not key-value pairs. What you want could be achieved with Jackson or any JSON parser for Java.

If you want to go for Jackson here's the code that will do the trick:

String json = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);

ObjectNode node = mapper.createObjectNode();
node.set("b", tree.get("b"));
node.set("d", tree.get("d"));
node.set("e", tree.get("e"));

String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);



回答2:


Your json path is correct, while json it self is not. It should be:

{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}

BTW there is good online testing resources for these purposes: http://jsonpath.com/




回答3:


Elements must be in single quotes.

$.['b','d','e']

Works fine for JsonPath from com.jayway.jsonpath:json-path:2.4.0




回答4:


You need to modify your JSON to (as said by Andremoniy)

{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}

and to select b,d,e use this

$.b,d,e


来源:https://stackoverflow.com/questions/40017445/selecting-a-subset-of-json-properties-and-values-using-jsonpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!