Update JSON Key Name in Python
Last Updated :
05 Feb, 2024
Working with JSON data is a common task in Python, and there are various scenarios where you might need to update the key names within a JSON object. In this article, we will explore five different simple and generally used methods to achieve this task, accompanied by code examples.
How to Update Json Key Name in Python?
Below, are the ways To Update JSON key names in Python.
Update JSON Key Name Using a Dictionary Comprehension
In this example, in the below Python code, a new dictionary (`updated_json`) is created by mapping keys from `original_json` to their corresponding values, using a `key_mapping` dictionary. If a key is not found in the `key_mapping`, it remains unchanged. The result is a modified JSON structure with updated key names.
Python3
original_json = {'old_key1': 'value1', 'old_key2': 'value2'}
key_mapping = {'old_key1': 'new_key1', 'old_key2': 'new_key2'}
updated_json = {key_mapping.get(key, key): value for key, value in original_json.items()}
print(updated_json)
Output :
{'new_key1': 'value1', 'new_key2': 'value2'}
Update Json Key Name Using JSON library
In this example, below Python code utilizes the `json` library to update key names within a JSON object. It loads the original JSON string into a dictionary (`json_data`), performs key updates using `pop` and assignment, and then converts the modified dictionary back to a JSON string (`updated_json`) using `json.dumps`.
Python3
import json
original_json = '{"old_key1": "value1", "old_key2": "value2"}'
json_data = json.loads(original_json)
json_data['new_key1'] = json_data.pop('old_key1')
json_data['new_key2'] = json_data.pop('old_key2')
updated_json = json.dumps(json_data)
print(updated_json)
Output :
{"new_key1": "value1", "new_key2": "value2"}
Update Json Key Name Using Pandas library
In this example, below code uses the Pandas library to update key names in a JSON-like structure. It converts the original JSON data to a DataFrame, renames columns, and then converts it back to a JSON string for printing.
Python3
import pandas as pd
original_json = {'old_key1': 'value1', 'old_key2': 'value2'}
df = pd.DataFrame([original_json])
df = df.rename(columns={'old_key1': 'new_key1', 'old_key2': 'new_key2'})
updated_json = df.to_json(orient='records')[1:-1]
print(updated_json)
Output :
{"new_key1":"value1","new_key2":"value2"}
Update Json Key Name Using a custom Function
In this example, below Python code defines a function `update_json_keys` that updates key names in a dictionary (`data`). It iterates through corresponding old and new key pairs, checks and updates the keys if present, and then demonstrates the function by updating keys in `original_json`.
Python3
def update_json_keys(data, old_keys, new_keys):
for old_key, new_key in zip(old_keys, new_keys):
if old_key in data:
data[new_key] = data.pop(old_key)
original_json = {'old_key1': 'value1', 'old_key2': 'value2'}
update_json_keys(original_json, ['old_key1', 'old_key2'], ['new_key1', 'new_key2'])
print(original_json)
Output :
{'new_key1': 'value1', 'new_key2': 'value2'}
Conclusion
In conclusion , Updating JSON key names in Python can be achieved through various methods, and the choice of method depends on the specific requirements of your task. Whether you prefer dictionary comprehensions, the json library, Pandas, jsonpath-rw, or a custom function, these approaches provide flexibility and ease of use for handling JSON data.
Similar Reads
Update Nested Dictionary - Python A nested dictionary in Python is a dictionary that contains another dictionary (or dictionaries) as its value. Updating a nested dictionary involves modifying its structure or content by:Adding new key-value pairs to any level of the nested structure.Modifying existing values associated with specifi
4 min read
Python MongoDB - Update_one() MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs.First create a database on which we perform the update_one() operation:Â Â Python3 # importing Mongoclient from
4 min read
Python - Dict of tuples to JSON In this article, we will discuss how to convert a dictionary of tuples to JSON. Method 1: Using json.dumps() This will convert dictionary of tuples to json Syntax: json.dumps(dictionary, indent) Parameters: Â dictionary is the input dictionary.indent specify the number of units of indentation Exampl
2 min read
Inventory Management with JSON in Python The Inventory Management system is used to manage store products and keep track of all goods stock and also we can use it to check the purchases history of the store. Basically, we are developing a system to manage/automate some processes of any retail store by using the computer. So by using this s
15+ min read
Add new keys to a dictionary in Python In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
Read, Write and Parse JSON using Python JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON. Example of JSON String s = '{"id":0
4 min read