在 Goessner 的实现中,JsonPath 可以返回 Path 或 Value,Value 是默认值,也是上面所有示例的返回值。
如果你更希望得到我们的查询所命中的元素的路径,这可以通过 Option.AS_PATH_LIST 选项来实现。例如:
// 设置选项
Configuration conf = Configuration.builder()
.options(Option.AS_PATH_LIST).build();
// 获取元素路径信息
List<String> pathList = using(conf).parse(json).read("$..author");
// 断言
assertThat(pathList).containsExactly(
"$['store']['book'][0]['author']",
"$['store']['book'][1]['author']",
"$['store']['book'][2]['author']",
"$['store']['book'][3]['author']");我们来看一个完整的示例:
package com.hxstrive.json_path;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.Predicate;
import java.util.List;
import java.util.Map;
/**
* Jayway JsonPath 示例
* @author hxstrive.com
*/
public class Demo12 {
public static void main(String[] args) {
String json = "{" +
" \"store\": {" +
" \"book\": [" +
" {" +
" \"category\": \"reference\"," +
" \"author\": \"Nigel Rees\"," +
" \"title\": \"Sayings of the Century\"," +
" \"price\": 8.95" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Evelyn Waugh\"," +
" \"title\": \"Sword of Honour\"," +
" \"price\": 12.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"Herman Melville\"," +
" \"title\": \"Moby Dick\"," +
" \"isbn\": \"0-553-21311-3\"," +
" \"price\": 8.99" +
" }," +
" {" +
" \"category\": \"fiction\"," +
" \"author\": \"J. R. R. Tolkien\"," +
" \"title\": \"The Lord of the Rings\"," +
" \"isbn\": \"0-395-19395-8\"," +
" \"price\": 22.99" +
" }" +
" ]," +
" \"bicycle\": {" +
" \"color\": \"red\"," +
" \"price\": 19.95" +
" }" +
" }," +
" \"expensive\": 10" +
"}";
// 返回代表评估点击路径的路径字符串列表
Configuration conf = Configuration.builder()
.options(Option.AS_PATH_LIST).build();
List<String> pathList = JsonPath.using(conf).parse(json).read("$..author");
for(String path : pathList) {
System.out.println("path: " + path);
}
}
}运行示例,输出结果如下:
path: $['store']['book'][0]['author'] path: $['store']['book'][1]['author'] path: $['store']['book'][2]['author'] path: $['store']['book'][3]['author']