- json.dumps(): 對數據進行編碼。
- json.loads(): 對數據進行解碼。
Python和JSON轉換對應表:
Python | JSON |
---|---|
dict | object |
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
代碼示例:
#!/usr/bin/python3
import json
# Python 字典類型轉換爲 JSON 對象
data = {
'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
print ("Python 原始數據:", repr(data))
print ("JSON 對象:", json_str)
輸出結果:
Python 原始數據: {‘url’: ‘http://www.runoob.com’, ‘no’: 1, ‘name’: ‘Runoob’}
JSON 對象: {“url”: “http://www.runoob.com”, “no”: 1, “name”: “Runoob”}
如果你要處理的是文件而不是字符串,你可以使用 json.dump() 和 json.load() 來編碼和解碼JSON數據
# 寫入 JSON 數據
with open('data.json', 'w') as f:
json.dump(data, f)
# 讀取數據
with open('data.json', 'r') as f:
data = json.load(f)