Open In App

How to Remove Key-Value Pair from a JSON File in Python

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a Python JSON file and our task is to remove a key-value pair in a JSON file in Python. In this article, we will see how we can remove a key-value pair in a JSON file in Python.

Remove Key-Value Pair from a JSON File in Python

Below are the possible approaches to Remove items from a JSON file In Python:

  • Using the pop() method
  • Using dictionary comprehension
  • Using the del statement
  • Using the update() method

input.json

{
  "website": "GeeksforGeeks",
  "topics": ["Algorithms", "Data Structures", "Python", "JavaScript"],
  "featured_article": {
    "title": "Introduction to JSON Parsing in Python",
    "author": "GeekAuthor123",
    "published_date": "2024-02-27"
  }
}

Remove Key-Value Pair in a Json File Using pop() Method

In this example, we are using the pop() method to remove a specified key, “featured_article”, from a JSON file (input.json). The script checks if the key exists in the JSON data before removal, and if found, it prints the removed key and its corresponding value. The updated JSON data is then saved to a new file, ‘output.json‘, preserving the modifications made during the removal process.

Python3




import json
 
# load JSON data from file
with open('input.json', 'r') as file:
    data = json.load(file)
 
# key to remove
key_to_remove = "featured_article"
 
# checking if the key exists before removing
if key_to_remove in data:
    removed_value = data.pop(key_to_remove)
    print(f"Removed key '{key_to_remove}' with value: {removed_value}")
 
# saving the updated JSON data back to the file
with open('output.json', 'w') as file:
    json.dump(data, file, indent=2)


Output:

Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}

output.json

{
  "website": "GeeksforGeeks",
  "topics": [
    "Algorithms",
    "Data Structures",
    "Python",
    "JavaScript"
  ]
}

Remove Key-Value Pair in a Json File Using Dictionary Comprehension

In this example, we are using dictionary comprehension to remove a specified key, “featured_article”, from a JSON file (input.json). The script checks if the specific key exists, and removes it if found. It utilizes dictionary comprehension to create an updated dictionary without the specified key. It prints the removed key and its associated value if the key is found. Finally, the updated data is returned to a new JSON file (output.json).

Python3




import json
 
# load JSON data from file
with open('input.json','r') as file:
    data = json.load(file)
 
# key to remove
key_to_remove = "featured_article"
 
# check if key exists
if key_to_remove in data.keys():
     
    # Add the key if it does not equal key_to_remove
    updated_data = {key : value for key, value in data.items() if key != key_to_remove }
    removed_value = data[key_to_remove]
     
    print(f"Removed key '{key_to_remove}' with value: {removed_value}")
 
else:
    print("Key does not exist")
 
 
# Write the updated json to json file
with open('output.json','w') as f:
 
    # write updated data
    json.dump(updated_data,f,indent=2)


Output:

Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}

output.json

{
  "website": "GeeksforGeeks",
  "topics": [
    "Algorithms",
    "Data Structures",
    "Python",
    "JavaScript"
  ]
}

Remove Key-Value Pair in a Json File Using del statement

In this example, we have used the del statement to remove a specified key, “featured_article“, from JSON data loaded from a file named ‘input.json’. The del statement deletes the key-value pair associated with the specified key in the JSON data. Finally, the updated JSON data, without the removed key, is written to a file named ‘output.json’.

Python3




import json
 
# load JSON data from file
with open('input.json','r') as file:
    data = json.load(file)
 
# key to remove
key_to_remove = "featured_article"
 
# check if key exists
if key_to_remove in data.keys():
 
    removed_value = data[key_to_remove]
     
    # Removing the key
    del data[key_to_remove]
     
    print(f"Removed key '{key_to_remove}' with value: {removed_value}")
 
else:
    print("Key does not exist")
 
 
# Write the updated json to json file
with open('output.json','w') as f:
 
    # write updated data
    json.dump(data,f,indent=2)


Output:

Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}

output.json

{
  "website": "GeeksforGeeks",
  "topics": [
    "Algorithms",
    "Data Structures",
    "Python",
    "JavaScript"
  ]
}

Remove Key-Value Pair Using update() Method

In this example, we have used the update method to remove a specific key, “featured_article“, from the loaded JSON data from a file named ‘input.json’. If the key exists, the script iterates over the data, updating a new dictionary “updated_data” with all key-value pairs except the one to be removed. Finally, it writes the updated JSON data to a file named “output.json“.

Python3




import json
 
# load JSON data from file
with open('input.json','r') as file:
    data = json.load(file)
 
# key to remove
key_to_remove = "featured_article"
 
# check if key exists
if key_to_remove in data.keys():
    updated_data = {}
     
    for key,value in data.items():
            if key != key_to_remove:
                updated_data.update({key : value})
            else:
                removed_value = value
         
    print(f"Removed key '{key_to_remove}' with value: {removed_value}")
 
else:
    print("Key does not exist")
 
 
# Write the updated json to json file
with open('output.json','w') as f:
 
    # write updated data
    json.dump(updated_data,f,indent=2)


Output:

Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}

output.json

{
  "website": "GeeksforGeeks",
  "topics": [
    "Algorithms",
    "Data Structures",
    "Python",
    "JavaScript"
  ]
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads