目录
1.背景
2.问题
3.参考资料
1.背景
在自动化测试脚本中,jsonpath确实是一个挺好用的小组件。网上已经有很多关于其基本使用方法的文档,这里就不再啰嗦了。本文想要提出的一个疑问是:如何在不使用正则表达式的前提下,通过jsonpath自己的语法完成模糊匹配的操作呢?类似SQL中的LIKE "%test%"
2.问题
以通用的JSON对象为例:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31data = { "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 } } }
目标:提取出书记标题中含有"ord"字段的内容。即,
复制代码
1
2
3
4
5
6
7
8
9
10
11{ "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }
解决方案一:
复制代码
1$.store.book[?(@ && @.title && /ord/.test(@.title))]
通过一些jsonpath在线解析工具,上面的这种提取方式的确可以提取到我们需要的内容。但当我们放到python代码中。如下方所示,就不能生效了。怀疑是因为这里有特殊字符"/"。可一直也没有找到如何转义
复制代码
1result = jsonpath.jsonpath(data, f"$.store.book[?(@ && @.title && /ord/.test(@.title))")
解决方案二:
复制代码
1$..book[?(@.author =~ /.*REES/i)]
这种方式和第一种一样,都含有一些特殊字符。在Python代码中就会失效。
笔者注意到,上述方式都是在import json这个库下去完成的,所以一直失效。
解决方案三:
导入库 from pyjsonpath import JsonPath,然后再采用类似方案二中的表达式即可。当然,下方的这种表达式也ok
复制代码
1
2result = JsonPath(data, "$.store.book[?(@.title =~ /.*?ord.*?/i)]").load()
3.参考资料
使用jsonpath进行字符串搜索 |
python-jsonpath解析_玉米丛里吃过亏的博客-CSDN博客_jsonpath python
Python3中JsonPath用法 - 漂泊的小虎 - 博客园
[SoapUI] JsonPath 语法 与 XPath 对比 - 开发者博
最后
以上就是魔幻鸡翅最近收集整理的关于Python中使用jsonpath进行模糊匹配的全部内容,更多相关Python中使用jsonpath进行模糊匹配内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复