python str 与json类型转换 ,即字符串类型和字典类型的转换
在写代码时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型
(1)str转json
python字符串转json对象,需要使用json模块的loads函数
# encoding: utf-8 print "str转json" import json string_a = '{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}' print "type(string_a): ", type(string_a) dict_a = json.loads(string_a) # json_str == dict print "dict_a: ", dict_a print "type(dict_a): ", type(dict_a)
输出结果:
str转json type(string_a): <type 'str'> dict_a: {u'accessToken': u'521de21161b23988173e6f7f48f9ee96e28', u'User-Agent': u'Apache-HttpClient/4.5.2 (Java/1.8.0_131)'} type(dict_a): <type 'dict'>
(2)json转str
# encoding: utf-8 print "json转str" import json json_b = {"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"} print "type(json_b): ", type(json_b) str_b = json.dumps(json_b) print "str_b: ", str_b print "type(str_b): ", type(str_b)
输出结果:
json转str type(json_b): <type 'dict'> str_b: {"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"} type(str_b): <type 'str'>
(3)可能遇到的问题
当引号嵌套时该如何处理呢?在str转json时,str格式引号问题导致失败报错。
# encoding: utf-8 import json #str = "{'accessToken': '521de21161b23988173e6f7f48f9ee96e28', 'User-Agent': 'Apache-HttpClient/4.5.2 (Java/1.8.0_131)'}" # A_Cluase str = '{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}' # B_Clause j = json.loads(str) print(j) print(type(j))
以上代码,咋一看没啥问题,但是运行时会出现错误
ValueError: Expecting property name: line 1 column 2 (char 1) 或者 json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
为什么呢?
因为字符串中,双引号在外围,单引号在内嵌,导致转换失败 而正确写法如下: ''' 记住字符串的正确写法是要转json的字符串中包含引号是应该: 单引号在外围,双引号在内部''' 解决方案:即将A_clause改成B_clause即可