python 字典与字符串相互转换

C:\Users\admin>python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import json                     # 导入json库
>>>
>>> data={'name':"python","age":20}  # data 是字典类型的数据
>>> type(data)
<class 'dict'>
>>>
>>> json_str=json.dumps(data)  # 字典转换为字符串
>>> type(json_str)
<class 'str'>
>>>
>>> d=json.loads(json_str) # 字符串转换为字典
>>> type(d)
<class 'dict'>
>>> d["name"]
'python'
>>> d["age"]
20
>>>

总结:
json.dumps() # 字典转换为字符串
json.loads() # 字符串转换为字典

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/108461063