0

I am creating a kind-of database in using the .JSON file and I want to delete a specific element of an array in a JSON file using Python language, but I can't do this how I want, here's what info.json file looks like:

{
    "dates": [
        {
            "date": "10/10",
            "desc": "test1"
        },
        {
            "date": "09/09",
            "desc": "test3"
        }
    ],
    "data": [
        {
            "name": "123",
            "infotext": "1234"
        },
        {
            "name": "!@#",
            "infotext": "!@#$"
        }
    ]
}

Here's what json_import.py file looks like:

def delete_data():
    name = input("Enter data name\n")
    with open("info.json", "r+") as f:
        file_data = json.load(f)
        for x in file_data["data"]:
            if x["name"] == name:
                file_data["data"].remove(x)
                f.seek(0)
                json.dump(file_data, f, indent = 4)

delete_data()
TERMINAL:
Enter data name
!@#

Expected:

{
    "dates": [
        {
            "date": "10/10",
            "desc": "test1"
        },
        {
            "date": "09/09",
            "desc": "test3"
        }
    ],
    "data": [
        {
            "name": "123",
            "datatext": "1234"
        }
    ]
}

Actual result:

{
    "dates": [
        {
            "date": "10/10",
            "desc": "test1"
        },
        {
            "date": "09/09",
            "desc": "test3"
        }
    ],
    "data": [
        {
            "name": "123",
            "datatext": "1234"

        }
    ]
} {
            "name": "!@#",
            "infotext": "!@#$"
        }
    ]
}

So how to fix it?

  • 2
    In general what your code should do is first read the file contents as you are doing, but with the file opened like this: `open("info.json", "r")` and then close the file. You should then manipulate the `dict` (as `file_data` is a `dict`) and then write it back to the file inside a: `with open("info.json", "w") as f:` – quamrana Oct 29 '22 at 15:59
  • Try looking at [Python, delete JSON element having specific key from a loop](https://stackoverflow.com/questions/52174334/python-delete-json-element-having-specific-key-from-a-loop?adlt=strict&toWww=1&redig=5766E32020294DA080CBDB1720C40FF6). – Alias Cartellano Oct 29 '22 at 16:27
  • I guess this question is similar to yours one: https://stackoverflow.com/questions/19201233/how-to-delete-json-object-using-python – Dmitriy Neledva Oct 29 '22 at 16:31

0 Answers0