Open In App

Update JSON Key Name in Python

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads