接口测试数据处理:
字典,字符串,json 转换:
数据类型:
a = None # None = null
b = False # boolean
c, d = 12, 10.6 # int float
e = \'asdd\' # str
f = [\'s\', \'e\'] # list,数组,可增删改查
g = (\'a\', \'s\', \'f\') # 元组(tuple),只能查
t = {
# 键:值
\'\': \'\',
\'\': \'\'
}
# 字典
# dict key: value key是唯一的,无序的
h = {
\'s\': 12,
\'f\': False,}
# 取出所有的key
keys = h.keys()
# 遍历所有的key
for i in list(keys):
print(\'%s = %s\'%(i, h[i]))
abc = {\'aa\': \'dd\', \'bb\': \'th\'}
aaa = str(abc) # 字典转str
bbb = eval(aaa) # str转字典
# 字典转json: json本质是字符串,只是按一定规则转换的
d_json = json.dumps(h)
# json(str)转字典 : 把json格式转换成字典格式
json_dict = json.loads(d_json)
传递参数 : data 与 json
# 传递json 参数:
import requests
url = \'xxxxxxxx\'
body = {
\'xxx\': \'xxx\',
\'xxx\': \'xxx\'
}
# body是json格式的
r = requests.post(url, json=body)
print(r.text)
import json
r = requests.post(url, data=json.dumps(body))
print(r.text)
返回json 处理:
requests里面自带解析器转字典:
print(r.json())
print(type(r.json()))
# 取出json中的\'result_sk_temp\'字段
# {"resultcode":"200","reason":"查询成功","result":{"sk":{"temp":"28","wind_direction":"东南风","wind_strength":"2级"
result = r.json()["result"][\'sk\'][\'temp\']
json模块转字典
import json
print(json.loads(r.text)) # json格式的str转dict
print(type(json.loads(r.text)))
--> # 查看返回内容,是字典格式才能转json
print(r.json()[\'reason\'])
print(r.json()[\'result\'][\'today\'][\'weather\'])