共計(jì) 904 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
要解析和修改 JSON 文件的內(nèi)容,可以使用 Python 的 json 模塊。
首先,我們需要將 JSON 文件讀取為 Python 的數(shù)據(jù)結(jié)構(gòu)。可以使用 json.load()
函數(shù)來實(shí)現(xiàn):
import json
# 讀取 JSON 文件
with open('data.json', 'r') as file:
data = json.load(file)
現(xiàn)在,data
變量將包含 JSON 文件的內(nèi)容,并且已經(jīng)轉(zhuǎn)換為 Python 的數(shù)據(jù)結(jié)構(gòu)(如字典、列表等)。
接下來,我們可以對(duì) data
進(jìn)行修改。例如,假設(shè)我們想修改 JSON 文件中的某個(gè)鍵的值:
# 修改鍵的值
data['key'] = 'new value'
或者,我們可以添加新的鍵值對(duì):
# 添加新的鍵值對(duì)
data['new_key'] = 'new value'
修改完成后,我們可以將修改后的數(shù)據(jù)寫入到 JSON 文件中。可以使用 json.dump()
函數(shù)來實(shí)現(xiàn):
# 寫入 JSON 文件
with open('data.json', 'w') as file:
json.dump(data, file)
這將會(huì)將修改后的數(shù)據(jù)寫入到原始的 JSON 文件中,覆蓋原來的內(nèi)容。
完整的代碼示例:
import json
# 讀取 JSON 文件
with open('data.json', 'r') as file:
data = json.load(file)
# 修改鍵的值
data['key'] = 'new value'
# 添加新的鍵值對(duì)
data['new_key'] = 'new value'
# 寫入 JSON 文件
with open('data.json', 'w') as file:
json.dump(data, file)
上述代碼會(huì)讀取名為 data.json
的 JSON 文件,然后修改其中的鍵值對(duì),并將修改后的數(shù)據(jù)寫回到原始的 JSON 文件中。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完