还有人不会用JsonPath?看这篇就够了!
目录
01 引入
02 语法
03 函数
04 过滤操作符
05 实例练习
06 读取Json
01 引入
JsonPath对于JSON来说就相当于XPATH对于XML,有一套自己的语法,类似于正则表达式,并提供了多种语言的实现版本,包括:Java、Javascript、Python和PHP。
Jayway JsonPath是JsonPath的java版本实现,是一个用于从Json文档中抽取指定信息的工具。
github地址:
https://github.com/json-path/JsonPath/
在POM中加入以下依赖
com.jayway.jsonpath json-path 2.6.0
02 语法
JsonPath中的“根成员对象”始终称为$,无论是对象还是数组。
JsonPath表达式有两种表示法
点表示法
$.store.book [0].title
括号表示法
$['store']['book'][0]['title']
03 函数
函数可以在路径的尾部被调用,函数的输入就是路径表达式的输出。
例如
$..data[?(@.extInfo.imgs.length()>0)].goodsId
04 过滤操作符
过滤表达式是用来过滤数组的逻辑表达式,使用时用类似[?(@.age > 18)]这样的表达式。注意,字符串必须用一组闭合的单引号或双引号。
05 实例练习
可通过下列链接路径测试JsonPath是否正确:
-
http://www.atoolbox.net/Tool.php?Id=792
-
https://www.json.cn/
实例
{ "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}
测试
06 读取Json
方法一:
List authors = JsonPath.read(json, "$.store.book[*].author");
该方法适合读取一次Json。若多次读取,会进行多次解析而浪费性能
方法二:
// 先解析,再多次读取Objectdocument = Configuration.defaultConfiguration().jsonProvider().parse(json);String author0 = JsonPath.read(document, "$.store.book[0].author");String author1 = JsonPath.read(document, "$.store.book[1].author");
方法三:
ReadContext ctx = JsonPath.parse(json);List authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");List<Map> expensiveBooks = JsonPath.using(configuration).parse(json).read("$.store.book[?(@.price > 10)]", List.class);