user14186442
user14186442

Reputation:

How to delete key and value from JSON

I'm making a tag feature for my bot and I've managed to make commands to create, use, and show the tags. Now I'm stuck on how to delete the key and value based on the tag given. For example !deletetag youtube would delete the youtube tag from the list below:

{
    "twitch": "https://www.twitch.tv/",
    "youtube": "https://www.youtube.com/",
    "ig": "https://www.instagram.com/",
    "twitter": "https://twitter.com/"
}

The reason I'm using a JSON file to store the tags is because the bot will only be used in one server of <100 people and it wouldn't contain more than 30-40 tags. Here is what I've tried:

@commands.command(name="deletetag",
                  help="Delete an existing tag.")
async def _deletetags(self, ctx, tag: str):
    with open('tags.json') as output:
        data = json.load(output)
        for key in data:
            del key[tag]

Upvotes: 3

Views: 12457

Answers (1)

DarrylG
DarrylG

Reputation: 17166

Placing my comment as answer for more easy reference.

# Remove key from dictionary
del data[tag]

# Serialize data and write back to file
with open('tags.json', 'w') as f: 
    json.dump(data, f) 

Upvotes: 4

Related Questions