json字符串⼤括号⾥的必须全部双引号python中,字典和json字符串互相转换,json中key和value必须是双引号
⼀,字典中,key和value可以是单引号或者是双引号
#⼀,字典转换为json字符串,字典中key和value可以是单引号或者是双引号,但是转换称json格式后,都是双引号
dic={'a':1,'b':'haha'}
st=json.dumps(dic)
print(st)
#⼆,字典转换为json字符串
dic={"a":1,"b":"haha"}
st=json.dumps(dic)
python json字符串转数组print(st)
打印结果
{"a": 1, "b": "haha"}
{"a": 1, "b": "haha"}
⼆,json字符串中,⼤括号内必须全部是双引号,⼤括号最外层是单引号,否者json转换为字典对象,会报错#三,⾮标准字符串转换字典,key和value是单引号,不是标准得json数据
st="{'a': 1, 'b': 'haha'}"
dic=json.loads(st)
print(dic)
报错:
File "D:\python\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "D:\python\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\python\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)
再⽐如:
# 三,⾮标准字符串转换字典
st=str({'a': 1, 'b': 'haha'})
dic=json.loads(st)
print(dic)
报错:
File "D:\python\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "D:\python\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\python\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)
合法得json字符串,⼤括号内必须全部是双引号
# 标准得json格式,是双引号,最外层是单引号
st = '{"a": 1, "b": "haha","c":{"d":1}}'
print(st)
dic = json.loads(st)
print(dic)
输出:
{"a": 1, "b": "haha","c":{"d":1}}
{'a': 1, 'b': 'haha', 'c': {'d': 1}}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论