之前在写Spring相关的测试用例时接触过JSONPath,但是当时并没有在意它,后续也没有再次碰到或使用过它。
现在在做项目时,需要解析外部接口返回的数据。那个接口返回的是一大段的JSON数据,我需要先在测试用例中解析那一段JSON格式的数据。当然我可以直接写一点java代码来解析,但是我发现这样效率挺慢,也不够直观。因为每次都要运行测试用例的解析代码。
要是能够直接对JSON数据进行查询和过滤就好了。当时抱着这样的想法,搜到了JSONPath概念,并且找到了直接JSONPath在线解析的网站。
JSONPath官网:
https://goessner.net/articles/JsonPath/
在线验证网站:
JSONPath的语法并不难,查看官网示例即可。对于如下的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
}
}
}
使用:$.store.book[?(@.category=='fiction' && @.price >= 8)],即可过滤出book的category为fiction且price大于等于8的数据。
截图如下:

参考连接:
1762





