JSON (JavaScript Object Notation) 是一種輕量級的數據交換格式。Python3 中可以使用 json 模塊來對 JSON 數據進行編解碼,主要包含了下面4個操作函數:
提示:所謂類文件對象指那些具有read()或者 write()方法的對象,例如,f = open('a.txt','r'),其中的f有read()方法,所以f就是類文件對象。
在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
data = {
'name': 'pengjunlee',
'age': 32,
'vip': True,
'address': {'province': 'GuangDong', 'city': 'ShenZhen'}
}
# 將 Python 字典類型轉換爲 JSON 對象
json_str = json.dumps(data)
print(json_str) # 結果 {"name": "pengjunlee", "age": 32, "vip": true, "address": {"province": "GuangDong", "city": "ShenZhen"}}
# 將 JSON 對象類型轉換爲 Python 字典
user_dic = json.loads(json_str)
print(user_dic['address']) # 結果 {'province': 'GuangDong', 'city': 'ShenZhen'}
# 將 Python 字典直接輸出到文件
with open('pengjunlee.json', 'w', encoding='utf-8') as f:
json.dump(user_dic, f, ensure_ascii=False, indent=4)
# 將類文件對象中的JSON字符串直接轉換成 Python 字典
with open('pengjunlee.json', 'r', encoding='utf-8') as f:
ret_dic = json.load(f)
print(type(ret_dic)) # 結果 <class 'dict'>
print(ret_dic['name']) # 結果 pengjunlee
注意:使用eval()能夠實現簡單的字符串和Python類型的轉化。
user1 = eval('{"name":"pengjunlee"}')
print(user1['name']) # 結果 pengjunlee