Manipulating Nested JSON Objects
In addition to traversing nested JSON data, you may also need to manipulate or update the JSON structure. Python's json
module provides various functions to help you with this task.
Modifying Nested JSON Data
To modify nested JSON data, you can first load the JSON data into a Python dictionary, update the desired values, and then dump the modified data back to a JSON string.
import json
## Load JSON data
json_data = '{"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "New York", "state": "NY"}}'
data = json.loads(json_data)
## Modify nested data
data["name"] = "Jane Smith"
data["address"]["city"] = "Los Angeles"
data["address"]["state"] = "CA"
## Dump modified data to JSON
updated_json = json.dumps(data, indent=2)
print(updated_json)
Output:
{
"name": "Jane Smith",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Los Angeles",
"state": "CA"
}
}
Adding or Removing Nested Elements
You can also add or remove nested elements in a JSON object. To add a new key-value pair, simply assign the new value to the desired key. To remove a key-value pair, you can use the del
keyword.
import json
## Load JSON data
json_data = '{"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "New York", "state": "NY"}}'
data = json.loads(json_data)
## Add a new nested element
data["address"]["zip_code"] = "10001"
## Remove a nested element
del data["address"]["state"]
## Dump modified data to JSON
updated_json = json.dumps(data, indent=2)
print(updated_json)
Output:
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"zip_code": "10001"
}
}
By using these techniques, you can efficiently manipulate nested JSON data in Python, allowing you to update, add, or remove elements as needed.