详解【python】str与json类型转换
在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型
str转json
python字符串转json对象,需要使用json模块的loads函数
import json str = '{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}' j = json.loads(str) print(j) print(type(j))
输出
{'accessToken': '521de21161b23988173e6f7f48f9ee96e28', 'User-Agent': 'Apache-HttpClient/4.5.2 (Java/1.8.0_131)'}
<class 'dict'>
json转str
import json j = {"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"} str = json.dumps(j) print(str) print(type(str))
输出
{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}
<class 'str'>
问题
写这篇文章主要是为了mark一个问题,在str转json时,str格式引号问题导致失败报错
看看下面这段代码
import json str = "{'accessToken': '521de21161b23988173e6f7f48f9ee96e28', 'User-Agent': 'Apache-HttpClient/4.5.2 (Java/1.8.0_131)'}" j = json.loads(str) print(j) print(type(j)) !
咋一看没啥问题,但是出现错误
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
为什么呢?
字符串中,双引号在外围,单引号在内嵌,导致转换失败
相关推荐
stulen 2020-08-15
fengzhiwu 2020-08-01
liusarazhang 2020-06-28
xiaobaif 2020-06-14
lemonzhangyan 2020-06-13
Crazyshark 2020-06-13
weikaixxxxxx 2020-06-13
有梦就能实现 2020-06-10
shengnanonly 2020-06-03
oraclemch 2020-05-30
poplpsure 2020-05-27
fujuan000 2020-04-30
zuihaobushi 2020-04-30
luckymaoyy 2020-04-29
xiaoseyihe 2020-04-28
JackLang 2020-04-25
菇星獨行 2020-04-20
jyj00 2020-03-26