# 保存
data = [2, 2, 6]
with open('data.json', 'w') as fp:
json.dump(data, fp)
# 读取
with open('data.json', 'r') as fs:
data = json.load(fs)
- json.dumps(): 对数据进行编码。
- json.loads(): 对数据进行解码。
在 json 的编解码过程中,Python 的原始类型与 json 类型会相互转换
Python 编码为 JSON 类型转换对应表:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON 解码为 Python 类型转换对应表:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
import json
# Python 字典类型转换为 JSON 对象
dic = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(dic)
print ("Python 原始数据:", repr(dic))
print ("JSON 对象:", json_str)