JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。它基於ECMAScript的一個子集。python
Python3 中能夠使用 json 模塊來對 JSON 數據進行編解碼,它包含了兩個函數:json
在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 |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
如下實例演示了 Python 數據結構與JSON數據結構之間的轉換:函數
#!/usr/bin/python3 import json # Python 字典類型轉換爲 JSON 對象 data1 = { 'no' : 1, 'name' : 'Test', 'url' : 'http://www.baidu.com' } json_str = json.dumps(data1) print ("Python 原始數據:", repr(data1)) print ("JSON 對象:", json_str) # 將 JSON 對象轉換爲 Python 字典 data2 = json.loads(json_str) print ("data2['name']: ", data2['name']) print ("data2['url']: ", data2['url'])
執行以上代碼輸出結果爲:編碼
Python 原始數據: {'no': 1, 'name': 'Test', 'url': 'http://www.baidu.com'} JSON 對象: {"no": 1, "name": "Test", "url": "http://www.baidu.com"} data2['name']: Test data2['url']: http://www.baidu.com
經過輸出的結果能夠看出,簡單類型經過編碼後跟其原始的repr()輸出結果很是類似。url
若是你要處理的是文件而不是字符串,你能夠使用 json.dump() 和 json.load() 來編碼和解碼JSON數據。例如:spa
# 寫入 JSON 數據 with open('data.json', 'w') as f: json.dump(data, f) # 讀取數據 with open('data.json', 'r') as f: data = json.load(f)