remove an element from json python

When you open a file in mode r+, you open it for reading and writing.

Then, you read the file, so the stream position moves to the end of the file.

Then, you write to the file, so it writes at the current stream position, which is the end of the file.

To fix this, you have two options:

Option 1:

Seek the position to the starting of the file using f.seek(0). Then write to the file. The problem with this is that it will only overwrite as much of the file as needs to be overwritten to dump the new json. The rest of the file won’t be overwritten, so you’ll end up with garbled json anyway. To fix this, you will need to truncate the rest of the file.

with open('factions.json', 'r+') as f:
    j = json.load(f)
    j.pop("Meme Faction")
    f.seek(0)
    json.dump(j, f, indent=4)
    f.truncate()

Gives the output:

{
    "Gamer Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    }
}

Option 2

Close the original file handle and open a new one for write-only. Then write to the file.

with open('factions.json', 'r+') as f:
    j = json.load(f)

j.pop("Meme Faction")
with open('factions.json', 'w') as f:
    json.dump(j, f, indent=4)

Gives the output:

{
    "Gamer Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top