Delete key and pair from Json file

Question:

I’m trying to delete a key and its pair from a json file . I tried the codes below but nothing triggers or work. Anyone can modify and assist me

reda.json file

[{"carl": 33}, {"carl": 55}, {"user": "user2", "id": "21780"}, {"user": "user2"}, {"user": "123"}, {"user": []}, {"user": []}]
import json

json_data = json.load(open('reda.json'))
k = "carl"
for d in json_data:
    if k in d:
        del d[k]

Asked By: Icezua

||

Answers:

When you load a JSON file into Python using json.load, it creates a copy of that JSON in Python. When that copy is changed, these changes are not reflected in the file.

So what you need to do is then transfer your changed copy back to the file.

This can be achieved via a method in the same json library as you’re using, dump. Additionally, we need to supply an additional parameter to open to specify that we are writing to the file, not just reading.

import json

json_data = json.load(open('reda.json'))
k = "carl"
for d in json_data:
    if k in d:
        del d[k]

json.dump(json_data, open('reda.json','w'))
References
  1. Python 3.11.0 Documentation: json.dump
  2. Python 3.11.0 Documentation: open
Answered By: Mous
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.