How To Delete A JSON Object From A List In Python

Delete a JSON object from a list in Python

To delete a JSON object from a list in Python, I can perform delete from a Json file or a Json string. Details of the article are below hope you will read it all. 

Delete a JSON object from a list in Python

Remove a Json object from a Json file containing a list

Example:

  • Import the json module to use the functions in it.
  • A list is written on the file ‘text.json’.
  • Use the json.load() function to deserialize a file into a Python object. After deserializing the file, we get a list of Python.
  • Remove an element from the list.
  • Create a new json file named ‘Output.json’ that stores the results of the Python list object after it has been converted back to a Json object by the json.dumps function.
[
    {"id": 1, "name": "Apple"},
    {"id": 2, "name": "Banana"},   
    {"id": 3, "name": "Coconut"}, 
    {"id": 4, "name": "Water Melon"}
]
import json
 
with open('text.json', 'r') as f:
  # The json.load function deserializes a file into a Python object
  data = json.load(f)
  for idx, obj in enumerate(data):
        if obj['name'] == 'Apple':
        	# Remove an element from the list
            data.pop(idx)
          
print('List after deleting a Json object:', data)
 
# Use the json.dumps() function convert Python object back to Json object
# Save the result on another file named 'Output.json'
with open('Output.json', 'w') as f2:
  f2.write( json.dumps(data, indent = 4))

Output:

<class 'list'>
List after deleting a Json object: [{'id': 2, 'name': 'Banana'}, {'id': 3, 'name': 'Coconut'}, {'id': 4, 'name': 'Water Melon'}]

Save the result on another file named ‘Output.json’.

[
    {
        "id": 2,
        "name": "Banana"
    },
    {
        "id": 3,
        "name": "Coconut"
    },
    {
        "id": 4,
        "name": "Water Melon"
    }
]

Remove a Json object from a Json string

Example:

  • Import the json module to use the functions in it.
  • Initialize a Json string.
  • Using the json.loads() function to parse the Json string we get a Python list.
  • Remove an element from the list.
  • Use the json.dumps() function to convert the Python list back to a Json object.
import json

JsonString = """
[
 {"id": 1, "name": "Apple"},
 {"id": 2, "name": "Banana"},
 {"id": 3, "name": "Coconut"},
 {"id": 4, "name": "Water Melon"}
]
"""
# Use the json.loads() parses that string
convert = json.loads(JsonString)
 
for index, obj in enumerate(convert):
        if obj['name'] == 'Apple':
        # Remove an element from the dictionary
            convert.pop(index)
          
print('Remove an element from a dictionary:', convert)
print(type(convert))

# Use the json.dumps() function convert Python object back to Json object
jsonAgain = json.dumps(convert)
print('Json object:', jsonAgain)

Output:

Remove an element from a dictionary: [{'id': 2, 'name': 'Banana'}, {'id': 3, 'name': 'Coconut'},{'id': 4, 'name': 'Water Melon'}]
<class 'list'>
Json object: [{"id": 2, "name": "Banana"}, {"id": 3, "name": "Coconut"}, {"id": 4, "name": "Water Melon"}]

Summary

Those are the ways to delete a JSON object from a list in Python. You can perform deletion from a Json file and save the result to a new file for easy editing or reuse. Hope you get it done soon.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *