我制作了一個 discordbot,我想洗掉 .json 檔案的鍵(通道 ID)和值(訊息 ID),但出現此錯誤:
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\baron_btjit4i\Desktop\Autrebot\Cogs\ticket.py", line 213, in on_raw_reaction_add
data.pop(str(channell.id))
KeyError: '932014068682858507'
我的json檔案是這樣的:
{"931966019612864623": "931966020808228922", "931979274074869811": "931979274884354048", "931981646561943603": "931981647354667058", "931982921231912971": "931982922058186803", "932003079451213894": "932003080352989203", "932010872006664212": "932010872790999140", "932014068682858507": "932014069953753098"}
我的代碼在那里:
with open(msg_start, 'r') as data_file:
data = json.load(data_file)
if channell.id in data: # channell.id = 932014068682858507
data.pop(str(channell.id))
with open(msg_start, 'w') as data_file:
data = json.dump(data, data_file)
你能幫我嗎 ?
uj5u.com熱心網友回復:
試試這個:
with open(msg_start, "r ") as data_file:
data = json.load(data_file)
data.pop(str(channell.id), None)
data_file.seek(0)
json.dump(data, data_file)
data_file.truncate()
uj5u.com熱心網友回復:
加載 json python 時將其轉換為 dict 所以只需按鍵洗掉并再次轉儲。我將處理加載和轉儲,因為它更簡單,但也適用于您讀取檔案,只需確保您閱讀了參考:
import json
values = '{"931966019612864623": "931966020808228922", "931979274074869811": "931979274884354048", "931981646561943603": "931981647354667058", "931982921231912971": "931982922058186803", "932003079451213894": "932003080352989203", "932010872006664212": "932010872790999140", "932014068682858507": "932014069953753098"}'
data = json.loads(values) # convert json to dict
type(data) # <class 'dict'>
del data["931966019612864623"]
ob = json.dumps(data) # convert to json
print(ob)
# '{"931979274074869811": "931979274884354048", "931981646561943603": "931981647354667058", "931982921231912971": "931982922058186803", "932003079451213894": "932003080352989203", "932010872006664212": "932010872790999140", "932014068682858507": "932014069953753098"}
參考JSON.loads
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/412323.html
標籤:
上一篇:Json檔案不可讀?
下一篇:將json轉換為C#類
