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?

3
  • 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: Commented Oct 29, 2022 at 15:59
  • Try looking at Python, delete JSON element having specific key from a loop. Commented Oct 29, 2022 at 16:27
  • I guess this question is similar to yours one: stackoverflow.com/questions/19201233/… Commented Oct 29, 2022 at 16:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.