Python3 JSON 數據解析
JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。 它基於ECMAScript的一個子集。
Python3 中可以使用json 模塊來對JSON 數據進行編解碼,它包含了兩個函數:
- 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 |
json.dumps 與json.loads 實例
以下實例演示了Python 數據結構轉換為JSON:
#!/usr/bin/python3 import json # Python 字典类型转换为 JSON 对象 data = { 'no' : 1, 'name' : 'w3big', 'url' : 'http://www.w3big.com' } json_str = json.dumps(data) print ("Python 原始数据:", repr(data)) print ("JSON 对象:", json_str)
執行以上代碼輸出結果為:
Python 原始数据: {'url': 'http://www.w3big.com', 'no': 1, 'name': 'w3big'} JSON 对象: {"url": "http://www.w3big.com", "no": 1, "name": "w3big"}
通過輸出的結果可以看出,簡單類型通過編碼後跟其原始的repr()輸出結果非常相似。
接著以上實例,我們可以將一個JSON編碼的字符串轉換回一個Python數據結構:
#!/usr/bin/python3 import json # Python 字典类型转换为 JSON 对象 data1 = { 'no' : 1, 'name' : 'w3big', 'url' : 'http://www.w3big.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'])
執行以上代碼輸出結果為:
ython 原始数据: {'name': 'w3big', 'no': 1, 'url': 'http://www.w3big.com'} JSON 对象: {"name": "w3big", "no": 1, "url": "http://www.w3big.com"} data2['name']: w3big data2['url']: http://www.w3big.com
如果你要處理的是文件而不是字符串,你可以使用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)