首页 > 编程 > Python > 正文

详解【python】str与json类型转换

2019-11-25 12:57:44
字体:
来源:转载
供稿:网友

在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型

str转json

python字符串转json对象,需要使用json模块的loads函数

import jsonstr = '{"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 jsonj = {"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 jsonstr = "{'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)

为什么呢?

字符串中,双引号在外围,单引号在内嵌,导致转换失败

以上所述是小编给大家介绍的【python】str与json类型转换详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表