原文:https://www.cnblogs.com/shapeL/p/9106437.html
前提:接口自动化测试中,存在依赖情况:test_02的某个请求参数的值,需要依赖test_01返回结果中某个字段的数据,所以就先需要拿到返回数据中特定字段的值。这里使用到python中jsonpath-rw库
1.下载安装
pip install jsonpath-rw
2.导入
from jsonpath_rw import jsonpath,parse
3.例子介绍
1.返回的match数据,但我们想要的是value数据
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match for match in jsonpath_expr.find(data)]) 运行结果: [DatumInContext(value='news', path=Fields('baz'), context=DatumInContext(value={'baz': 'news'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA850>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None)))), DatumInContext(value='music', path=Fields('baz'), context=DatumInContext(value={'baz': 'music'}, path=<jsonpath_rw.jsonpath.Index object at 0x025CA770>, context=DatumInContext(value=[{'baz': 'news'}, {'baz': 'music'}], path=Fields('foo'), context=DatumInContext(value={'foo': [{'baz': 'news'}, {'baz': 'music'}]}, path=This(), context=None))))]
2.获取匹配的数据match.value
jsonpath_expr = parse('foo[*].baz') data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match.value for match in jsonpath_expr.find(data)])
运行结果:
['news', 'music']
3.match.value返回数据是一个list,我们要获取特定的值
data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match.value for match in jsonpath_expr.find(data)][0]) 运行结果: news