在做接口自动化,测试断言时,我们经常需要提取接口的的响应数据字段,以前用过jsonpath,有几篇相关文章,可以参考下(Python深层解析json数据之JsonPath、【Jmeter篇】后置处理器之正则提取器、Json提取器 、Jmeter之json提取器实战(二)、Jmeter之json条件提取实战(三) )今天我们来介绍下jmespath用法,可以帮我们进行数据的灵活提取,下面通过案例来说明jmespath在python的使用。
jmespath官方文档
https://jmespath.org/tutorial.html#projections
jmespath安装
pip install jmespath
字典,通过key名称提取
import jmespath
dict_1 = {"a": "foo", "b": "bar", "c": "baz"}
print(jmespath.search("c",dict_1))
baz
嵌套字典,层级提取
import jmespath
dict_1 = {"a": {"b": {"c": {"d": "value"}}}}
print(jmespath.search("a.b.c.d",dict_1))
value
import jmespath
dict_1 = {"a": {"b": {"c": {"d": "value"}}}}
print(jmespath.search("a.b.c",dict_1))
{'d': 'value'}
列表,通过索引提取
import jmespath
list_1 = ["a", "b", "c", "d", "e", "f"]
print(jmespath.search("[1]",list_1))
b
列表、字典嵌套提取
import jmespath
source = {"a": {
"b": {
"c": [
{"d": [0, [1, 2]]},
{"d": [3, 4]}
]
}
}}
print(jmespath.search("a.b.c[0].d[1][0]",source))
1
切片提取列表中值
import jmespath
source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(jmespath.search("[0:5]",source))
[0, 1, 2, 3, 4]
import jmespath
source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(jmespath.search("[5:10]",source))
[5, 6, 7, 8, 9]
import jmespath
source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(jmespath.search("[:5]",source))
[0, 1, 2, 3, 4]
import jmespath
source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(jmespath.search("[::2]",source))
[0, 2, 4, 6, 8]
列表取值使用 * 通配符
1、取出列表中所有 first对应的值
people[*].first
import jmespath
source = {
"people": [
{"first": "James", "last": "d"},
{"first": "Jacob", "last": "e"},
{"first": "Jayden", "last": "f"},
{"missing": "different"}
],
"foo": {"bar": "baz"}
}
print(jmespath.search("people[*].first",source))
['James', 'Jacob', 'Jayden']
2、取出列表中前2个first 对应的值