python返回结果取值字典取值、正则取值、jsonpath解析取值
程序员文章站
2022-04-02 11:10:09
做接口测试的时候,大部分情况下返回的是json数据,我们需要对返回的json断言。或者取出需要的值常规的字典取值result = { "code": 1, "data": [ { "age": 16, "create_time": "2020-11-11", "id": 1, "mail": "1172379@163.com", "name": "g...
做接口测试的时候,大部分情况下返回的是json数据,我们需要对返回的json断言。或者取出需要的值,下边介绍取值需要的数据的三种方法,正则和jsonpath可以解决不知道需要取出的值得位置的解决方法(数据值太多情况)
- 常规的字典取值
result = {
"code": 1,
"data": [
{
"age": 16,
"create_time": "2020-11-11",
"id": 1,
"mail": "1172379@163.com",
"name": "guiyin",
"sex": "L"
},
{
"age": 18,
"create_time": "2020-11-11",
"id": 2,
"mail": "123445@163.com",
"name": "guiyin222",
"sex": "XXL"
}
],
"msg": "success!"
}
# 字典取值断言
assert result["code"] == 1
assert result["msg"] == "success!"
assert result["data"][0]["name"] == "guiyin"
- 正则取值
比如我想判断返回的结果里面有没有 “name”: “guiyin” 并且你不知道它是 data 列表中的第几个,这种情况断言就写的很复杂了。
可以用万能的正则取值,正则只能是针对字符串取值,dict 对象先转 json 字符串。 - jsonpath解析取值
jsonpath常用语法
import re
import json
import jsonpath as jsonpath
result = {
"code": 1,
"data": [
{
"age": 16,
"create_time": "2020-11-11",
"id": 1,
"mail": "1172379@163.com",
"name": "guiyin",
"sex": "L"
},
{
"age": 18,
"create_time": "2020-11-11",
"id": 2,
"mail": "123445@163.com",
"name": "guiyin222",
"sex": "XXL"
}
],
"msg": "success!"
}
# 断言data中包含"name": "guiyin"
result_to_json = json.dumps(result)
print(result_to_json) # 先转json
# 方法1 正则取值
res = re.findall('"name": "(.+?)"', result_to_json) # 正则从json中取值
print(res)
assert "guiyin" in res
# 方法2 直接判断包含
assert '"name": "guiyin"' in result_to_json
#jsonpath用法
msg = jsonpath.jsonpath(result, '$.msg')
print(msg) # 输出结果 ['success!']
names = jsonpath.jsonpath(result, '$..name')
print(names) # 输出结果 ['yoyo', 'yoyo111']
no = jsonpath.jsonpath(result, '$..guiyin')
print(no) # 找不到是结果是 False
本文地址:https://blog.csdn.net/guiyin1150/article/details/109614662