How to Delete a JSON Object in Python?

Estimated read time 2 min read

To delete a JSON object in Python, you can use the del statement to remove a key-value pair from a dictionary, which is the equivalent of deleting an object from a JSON file. Here’s an example:

# Sample JSON object
my_json = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Display original JSON object
print("Original JSON object:")
print(my_json)

# Delete a key-value pair from the JSON object
del my_json['age']

# Display updated JSON object
print("Updated JSON object:")
print(my_json)

In this example, the del statement is used to delete the age key-value pair from the my_json dictionary, which is equivalent to deleting the "age": 30 object from the JSON file. The del statement takes the form del dictionary[key], where dictionary is the name of the dictionary and key is the key of the key-value pair you want to delete.

Note that the del statement will raise a KeyError if the key does not exist in the dictionary. So, make sure to check if the key exists in the JSON object before attempting to delete it to avoid any errors. You can use the in operator to check if a key exists in a dictionary, like this:

if 'age' in my_json:
    del my_json['age']

This will first check if the key 'age' exists in the my_json dictionary, and if so, it will delete the key-value pair.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply