Skip to content
Advertisement

how to delete json object using python?

I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the JSON file.

My JSON file is:

JavaScript

I want to delete the JSON object with ename mark.

As I am new to python I tried to delete it by converting objects into dict but it is not working. Is there any other way to do it? i tried this one:

JavaScript

Advertisement

Answer

Here’s a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

JavaScript

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you’ve reached the end of the for loop (you don’t want to modify the list while you iterate through it).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement