python3:jsonpath-rw处理Json对象
前提:接口自动化测试中,存在依赖情况:test_02的某个请求参数的值,需要依赖test_01返回结果中某个字段的数据,所以就先需要拿到返回数据中特定字段的值。这里使用到python中jsonpath-rw库
1.下载安装
pip installjsonpath-rw
2.导入
from jsonpath_rw import jsonpath,parse
3.例子介绍
1.返回的match数据,但我们想要的是value数据
jsonpath_expr = parse('foo[*].baz') 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)])<br />运行结果:<br />['news', 'music']
3.match.value返回数据是一个list,我们要获取特定的值
jsonpath_expr = parse('foo[*].baz') data = {'foo': [{'baz': 'news'}, {'baz': 'music'}]} print([match.value for match in jsonpath_expr.find(data)][0]) 运行结果: news
相关推荐
sailxu00 2020-06-21
somebodyoneday 2020-06-01
adonislu 2020-05-29
fengchao000 2020-05-07
AngelaDan 2020-01-07
somebodyoneday 2019-12-27
四叶草 2019-12-25
fengchao000 2019-12-12
GhostLWB 2019-12-10
baijinswpu 2019-12-09
somebodyoneday 2019-12-06
yigeng 2016-08-10
咸鱼的星空 2015-04-07
chinewwen 2018-08-17
MYSQL轻松学 2018-08-21
youmianzhou 2018-07-31
Yugi000 2013-11-18
忘 2014-03-10
张明云的知识共享 2018-05-29