json模块,字典和字符串相互转换

一、字典 转 字符串

方法一:json.dumps() ,不管字典里是单引号还是双引号,都可以用json.dumps()转换成字符串,且转后都为双引号!

import json
a = {'name':'lily','age':18}
b = {"name":"lily","age":18}
print(json.dumps(a))
print(json.dumps(b))
返回

{"name": "lily", "age": 18}
{"name": "lily", "age": 18}

方法二:str (),用str将字典转成字符串后,双引号变成了单引号

a = {'name':'lily','age':18}
b = {"name":"lily","age":18}
print('a:',str(a))
print('b:',str(b))
返回

a: {'name': 'lily', 'age': 18}
b: {'name': 'lily', 'age': 18}

 

二、字符串 转 字典

方法一、json.loads() ,要求json串格式中必须的双引号!!!转后双引号变为单引号

import json
a = {'name':'lily','age':18}
c = json.dumps(a)
print('c=',c)

print(json.loads(c))
返回

c= {"name": "lily", "age": 18}
{'name': 'lily', 'age': 18}

 

 

json串为单引号时,用json.loads()会报错:由于json的key没有双引号,导致json解析错误的

a = {"name":"lily","age":18} d = str(a) print('d=',d) print(json.loads(d))
返回报错信息

d= {'name': 'lily', 'age': 18}
Traceback (most recent call last):
File "/Users/PycharmProjects/FirstScrip/lijun/op_json.py", line 14, in <module>
print(json.loads(d))
File "/Users/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Users/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/anaconda3/lib/python3.6/json/decoder.py", line 355, 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)



 

posted @ 2018-03-16 10:49  水中一粒沙  阅读(693)  评论(0编辑  收藏  举报