首页 > Web开发 > 详细

jsonpath-rw处理json对象

时间:2020-05-29 00:01:29      阅读:132      评论:0      收藏:0      [点我收藏+]

接口自动化测试中,存在依赖情况:test_04的某个请求参数的值依赖test_03返回结果中的某个字段的数据,所以就需要拿到返回数据中特定字段的值。这里使用到python中的jsonpath-rw库

 

1、下载安装

pip install jsonpath-rw

 

2、导入

from jsonpath_rw import jsonpath,parse

 

3、例子介绍

1.返回的match数据

jsonpath_expr = parse(addCar.product)
data = {addCar:{‘product‘: [{‘id: ‘1‘,‘price‘:‘38‘}, {id: ‘32‘,‘price‘:‘19‘}]}}
print([match for match in jsonpath_expr.find(data)])

运行结果:[DatumInContext(value=[{‘id‘: ‘1‘, ‘price‘: ‘38‘}, {‘id‘: ‘32‘, ‘price‘: ‘19‘}], path=Fields(‘product‘), context=DatumInContext(value={‘product‘: [{‘id‘: ‘1‘, ‘price‘: ‘38‘}, {‘id‘: ‘32‘, ‘price‘: ‘19‘}]}, path=Fields(‘addCar‘), context=DatumInContext(value={‘addCar‘: {‘product‘: [{‘id‘: ‘1‘, ‘price‘: ‘38‘}, {‘id‘: ‘32‘, ‘price‘: ‘19‘}]}}, path=This(), context=None)))]

2.获取匹配的数据match.value

from jsonpath_rw import jsonpath,parse
data = {"addCar": {"product": [{"id": "1","price": "38"},{"id": "32", "price": "19"},]}}
jsonpath_expr = parse("addCar.product")
result = [match.value for match in jsonpath_expr.find(data)]
print(result)
运行结果: [[{‘id‘: ‘1‘, ‘price‘: ‘38‘}, {‘id‘: ‘32‘, ‘price‘: ‘19‘}]]

3.获取价格

from jsonpath_rw import jsonpath,parse

data = {"addCar": {"product": [{"id": "1","price": "38"},{"id": "32", "price": "19"},]}}
jsonpath_expr = parse("addCar.product[*].price")
result = [match.value for match in jsonpath_expr.find(data)]
print(result)
运行结果: [‘38‘, ‘19‘]

官方实例

1.提取值

result = [match.value for match in jsonpath_expr.find({‘foo‘:[{‘baz‘:1}, {‘baz‘:2}]})]
print(result)

>>>[1, 2]

2.获取匹配值对应的路径

from jsonpath_rw import jsonpath,parse
jsonpath_expr = parse(‘foo[*].baz‘)
result = [str(match.full_path) for match in jsonpath_expr.find({‘foo‘: [{‘baz‘: 1}, {‘baz‘: 2}]})]
print(result)

>>>[‘foo.[0].baz‘, ‘foo.[1].baz‘]

3.自动提供id

from jsonpath_rw import jsonpath,parse
result = [match.value for match in parse(‘foo[*].id‘).find({‘foo‘: [{‘id‘: ‘bizzle‘}, {‘baz‘: 3}]})]
print(result)

>>>[‘bizzle‘]

jsonpath.auto_id_field = ‘id‘
result = [match.value for match in parse(‘foo[*].id‘).find({‘foo‘: [{‘id‘: ‘bizzle‘}, {‘baz‘: 3}]})]

print(result)

>>>[‘foo.bizzle‘, ‘foo.[1]‘]

4.扩展功能之一 命名操作符 `parent`

result = [match.value for match in parse(‘a.*.b.`parent`.c‘).find({‘a‘: {‘x‘: {‘b‘: 1, ‘c‘: ‘number one‘}, ‘y‘: {‘b‘: 2, ‘c‘: ‘number two‘}}})]
print(result)

>>>[‘number one‘, ‘number two‘]

更多请查看参考连接

jsonpath-rw处理json对象

原文:https://www.cnblogs.com/DeryKong/p/12983400.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!