使用 JSONPath 选择 JSON 属性和值的子集

Selecting a subset of JSON properties and values using JSONPath

给出一个 JSON 赞:

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

如何 select 出 bde 以获得以下 JSON?

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

我想要一个 JSON 对象,而不仅仅是 245 值?

这是我正在尝试但失败的方法:

$.[b,d,e]

您的 json 路径是正确的,而 json 它自己不是。应该是:

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

顺便说一句,有用于这些目的的良好在线测试资源:http://jsonpath.com/

您需要将 JSON 修改为(如 Andremoniy 所说)

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

然后 select b,d,e 使用这个

$.b,d,e

JSON路径不适合您要实现的目标:JSON路径设计为 select 值而不是键值对。您可以使用 Jackson 或 Java 的任何 JSON 解析器来实现您想要的。

如果您想选择 Jackson,请使用以下代码:

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);

元素必须用单引号引起来。

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

适用于来自 com.jayway.jsonpath:json-path:2.4.0

的 JsonPath