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)
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}}

 

posted @ 2020-12-24 17:21  年轻人——001  阅读(2851)  评论(1编辑  收藏  举报