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 List in Python
In Python Programming, a list is a sequence of a data structure that is mutable. This means that the elements of a list can be modified to add, delete, or update the values. In this article we will explore various ways to update the list. Let us see a simple example of updating a list in Python.Pyth
2 min read
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 Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In
2 min read
Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Pa
2 min read
json.load() in Python
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Pytho
3 min read
json.loads() in Python
JSON is a lightweight data format used for storing and exchanging data across systems. Python provides a built-in module called json to work with JSON data easily. The json.loads() method of JSON module is used to parse a valid JSON string and convert it into a Python dictionary. For example:Pythoni
4 min read
How to update a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on a disk. What pickle does is that it âserializesâ the object first before writing it to file. Pickling is a way to convert a python object (list, d
3 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