1. 使用 Python 內(nèi)置模塊 json 解析 JSON 數(shù)據(jù) 通過(guò) Python 內(nèi)置的 json 模塊可以解析 JSON 格式的數(shù)據(jù),使用方法很簡(jiǎn)單。
以下是提取JSON數(shù)據(jù)中所有內(nèi)容的例子:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/11101.html
import json
# JSON 格式的數(shù)據(jù)
data = '{"name": "小明", "age": 18, "gender": "男"}'
# 將 JSON 格式的數(shù)據(jù)轉(zhuǎn)為 Python 對(duì)象
json_data = json.loads(data)
# 直接打印 Python 對(duì)象,即可得到整個(gè) JSON 數(shù)據(jù)
print(json_data)
上面的代碼中,首先定義一個(gè)包含 JSON 數(shù)據(jù)的字符串變量 data,然后使用 json.loads() 方法將其轉(zhuǎn)為 Python 對(duì)象,并將結(jié)果保存到 json_data 變量中。最后直接打印 Python 對(duì)象即可得到整個(gè) JSON 數(shù)據(jù)。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/11101.html
如果你想要獲取指定的內(nèi)容,可以通過(guò)鍵值對(duì)來(lái)訪問(wèn)。以下是提取JSON數(shù)據(jù)中指定內(nèi)容的例子:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/11101.html
import json
# JSON 格式的數(shù)據(jù)
data = '{"name": "小明", "age": 18, "gender": "男"}'
# 將 JSON 格式的數(shù)據(jù)轉(zhuǎn)為 Python 對(duì)象,并訪問(wèn)指定內(nèi)容
json_data = json.loads(data)
print(json_data['name']) # 獲取 name 的值
print(json_data['age']) # 獲取 age 的值
print(json_data['gender']) # 獲取 gender 的值
上面的代碼中,我們通過(guò)訪問(wèn) json_data 對(duì)象中的鍵來(lái)獲取指定的值。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/11101.html
文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.hvig.cn/11101.html


評(píng)論