有没有办法从JsonPath获取路径和价值?

时间:2019-01-16 15:44:08

标签: json jsonpath

我正在尝试使用JsonPath从以下JSON对象获取路径和值:

[
  {
    "id": 1,
    "person": {
      "name": "john",
      "age": "28"
    }
  },
  {
    "id": 2,
    "person": {
      "name": "jane",
      "age": "25"
    }
  }
]

使用路径时:"$[*].person.name",我将返回["john", "jane"]。 我想找回这样的东西:

    [{"john", "$[0].person.name"},
     {"jane", "$[1].person.name"}]

我需要该值和找到它的确切路径。

1 个答案:

答案 0 :(得分:1)

您可以分别读取路径和值,然后将结果放在一起。

下面是使用Jayway JsonPath的示例:

String json = "[\n" +
        "  {\n" +
        "    \"id\": 1,\n" +
        "    \"person\": {\n" +
        "      \"name\": \"john\",\n" +
        "      \"age\": \"28\"\n" +
        "    }\n" +
        "  },\n" +
        "  {\n" +
        "    \"id\": 2,\n" +
        "    \"person\": {\n" +
        "      \"name\": \"jane\",\n" +
        "      \"age\": \"25\"\n" +
        "    }\n" +
        "  }\n" +
        "]";

Object parse = Configuration.defaultConfiguration()
        .jsonProvider()
        .parse(json);

JsonPath path = JsonPath.compile("$[*].person.name");

// read the paths
JSONArray asPaths = path.read(parse, Configuration.builder()
        .options(Option.AS_PATH_LIST).build());
String[] paths = asPaths.toArray(new String[asPaths.size()]);

// read the values
JSONArray asValues = path.read(parse);
String[] values = asValues.toArray(new String[asValues.size()]);

// put the paths and values together using the array indexes
Map<String, String> valuesAndPaths = new HashMap<>();
for (int i = 0; i < values.length; i++) {
    valuesAndPaths.put(values[i], paths[i]);
}

for (Map.Entry<String, String> entry : valuesAndPaths.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

这将打印出来:

john, $[0]['person']['name']
jane, $[1]['person']['name']