1. 程式人生 > 其它 >使用Python解析JSON

使用Python解析JSON

JSON (JavaScriptObject 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