- json.dumps():对数据进行编码,dictionary 转换为 JSON 对象。
- json.loads():对数据进行解码,JSON 对象 转换为 dictionary。
在j son 的编码/解码过程中,Python 的原始类型与 json 类型会相互转换,具体的转化对照如下:
字符串形式转换:(语法是json.dumps(),不是json.dump(),有个s,不要忘记!json.loads()也是):
import json
# Python 字典类型
data = {
'no': 1,
'name': 'Runoob',
'url': 'http://www.runoob.com'
}
# dictionary 转换为 JSON 对象
json_str = json.dumps(data)
# JSON 对象 转换为 dictionary
data2 = json.loads(json_str)
print("Python 原始数据:", repr(data))
print("JSON 对象:", json_str)
print("Python:", data2['name'])
# 输出为:
# Python 原始数据: {'no': 1, 'name': 'Runoob', 'url': 'http://www.runoob.com'}
# JSON 对象: {"no": 1, "name": "Runoob", "url": "http://www.runoob.com"}
# Python: Runoob
如果处理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 来编码和解码JSON数据。(json.dump(),不是json.dumps(),没有s)
# 写入 JSON 数据
with open('data.json', 'w') as f:
json.dump(data, f)
# 读取数据
with open('data.json', 'r') as f:
data = json.load(f)