How to modify a key-value pair in a JSON object in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To modify a key-value pair in a JSON object in Python, you need to first parse the JSON data into a Python object using the json module’s loads() method. You can then modify the desired key-value pair using dictionary-style indexing, and then convert the modified Python object back into JSON format using the json module’s dumps() method.

Here’s an example:

import json

# Example JSON data
json_str = '{"name": "John", "age": 30, "city": "New York"}'

# Parse JSON data into Python object
data = json.loads(json_str)

# Modify a key-value pair
data["age"] = 40

# Convert modified Python object back into JSON format
json_str_modified = json.dumps(data)

# Print the modified JSON data
print(json_str_modified)

This will output:

{"name": "John", "age": 40, "city": "New York"}

As you can see, the age key-value pair has been modified to have a value of 40 instead of 30.

Tags: