使用场景
在做接口自动化测试的时候,测试用例是写在excel中,在读取测试用例的过程中,字段类型都会转为字符串,但在发送请求参数的数据中有些是要转为dict,才可以正常得到响应值。所以这篇文章给大家介绍3种str-->dict方法:
上干货
干货一:eval()
user_info="{'username':'list','password':123456,'age':18,'sex':'man','hobby':'ball'}"
#转化前类型是:str
print(type(user_info))
print(eval(user_info))
#转化后类型是:dict
print(type(eval(user_info)))
----------------------------------------------------------------------------------------------------
<class 'str'>
{'username': 'list', 'password': 123456, 'age': 18, 'sex': 'man', 'hobby': 'ball'}
<class 'dict'>
Process finished with exit code 0
warring:百度上说用eval方法会有安全性问题,有兴趣的自行百度,这里不做过多解释
干货二:json.loads()
import json
user_info="{'username':'list','password':123456,'age':18,'sex':'man','hobby':'ball'}"
print(type(user_info))
print(json.loads(user_info))
----------------------------------------------------------------------------------------------------
Traceback (most recent call last):
File "E:\apiAutoTest\str_dict.py", line 16, in <module>
print(type(json.loads(user_info_1)))
File "C:\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python39\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
###############################################################################################
import json
user_info='{"username":"list","password":123456,"age":18,"sex":"man","hobby":"ball"}'
user_info_1="{'username':'list','password':123456,'age':18,'sex':'man','hobby':'ball'}"
print(type(user_info))
print(json.loads(user_info))
print(type(json.loads(user_info)))
----------------------------------------------------------------------------------------------------
<class 'str'>
{'username': 'list', 'password': 123456, 'age': 18, 'sex': 'man', 'hobby': 'ball'}
<class 'dict'>
Process finished with exit code 0
warring:报错原因是由于:json.loads()只能识别key:value加了双引号的,单引号报错,要使用json.loads()必须严格遵守规则。
干货三:ast.literal_eval()
import ast
user_info='{"username":"list","password":123456,"age":18,"sex":"man","hobby":"ball"}'
print(type(user_info))
print(ast.literal_eval(user_info))
print(type(ast.literal_eval(user_info)))
----------------------------------------------------------------------------------------------------
<class 'str'>
{'username': 'list', 'password': 123456, 'age': 18, 'sex': 'man', 'hobby': 'ball'}
<class 'dict'>
Process finished with exit code 0
warring:这种方法解决的json.loads()的单双引号问题。参考了一些博主也说解决了eval的安全性问题,具体是什么安全性问题,大家自行百度
image.png
有帮助到的可以给我点一下关注哦!!!
谢谢啦~~
网友评论