Marcucus _
Marcucus _

Reputation: 98

How to really delete a key of a .json in python

I make a discordbot and I want to delete key (channel id) and value (message id) of a .json file but I've this error:

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'

My json file like this:

{"931966019612864623": "931966020808228922", "931979274074869811": "931979274884354048", "931981646561943603": "931981647354667058", "931982921231912971": "931982922058186803", "932003079451213894": "932003080352989203", "932010872006664212": "932010872790999140", "932014068682858507": "932014069953753098"}

And my code is there:

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)

Can you help me please ?

Upvotes: 1

Views: 1667

Answers (2)

Franz Gastring
Franz Gastring

Reputation: 1130

When loading a json python convert it to a dict so just delete by key and dump again. I will do with loads and dumps because is more simple but works for you reading a file too, just make sure you read the reference:

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"} 

Reference JSON.loads

Upvotes: 1

Remco646
Remco646

Reputation: 141

Try this:

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()

Upvotes: 2

Related Questions