JSON (JavaScript Object Notation) is commonly used to store structured data in files. In Python, data can be added to existing JSON content by reading the file, updating the data, and writing the updated content back to the file.
Update a JSON String
Here, a JSON string is first converted into a Python dictionary. New data is then appended to the dictionary and converted back into JSON format.
import json
data = '{"company":"TechWorld","city":"Delhi"}'
new_data = {"country": "India"}
json_data = json.loads(data)
json_data.update(new_data)
print(json.dumps(json_data))
Output
{"company": "TechWorld", "city": "Delhi", "country": "India"}
Explanation: json.loads() function converts the JSON string into a Python dictionary. The update() method adds the new key-value pair, and json.dumps() converts the updated dictionary back into a JSON string.
Add a New Record to a JSON File
Here, a new record is added to an existing list stored inside a JSON file. Sample JSON File (data.json):
{
"employees": [
{
"name": "David",
"role": "Intern"
}
]
}
The following code appends a new employee record to the employees list.
import json
new_employee = { "name": "Jake",
"role": "Software Engineer" }
with open("data.json", "r+") as file:
data = json.load(file)
data["employees"].append(new_employee)
file.seek(0)
json.dump(data, file, indent=4)
Updated JSON File
{
"employees": [
{
"name": "David",
"role": "Intern"
},
{
"name": "Jake",
"role": "Software Engineer"
}
]
}
Explanation: json.load() function reads the existing JSON data into a Python dictionary. The append() method adds the new employee record to the employees list, and json.dump() writes the updated data back to the file.
Add Multiple Records to a JSON File
If multiple records need to be added at once, the extend() method can be used to insert all records into the existing list. Sample JSON File (data.json):
{
"employees": [
{
"name": "David",
"role": "Intern"
}
]
}
import json
new_employees = [ {"name": "Emily", "role": "Designer"},
{"name": "Rose", "role": "Developer"} ]
with open("data.json", "r+") as file:
data = json.load(file)
data["employees"].extend(new_employees)
file.seek
json.dump(data, file, indent=4)
Updated JSON File
{
"employees": [
{
"name": "David",
"role": "Intern"
},
{
"name": "Emily",
"role": "Designer"
},
{
"name": "Rose",
"role": "Developer"
}
]
}
Explanation: json.load() function loads the existing JSON data. The extend() method adds all records from new_employees to the employees list in a single operation. Finally, json.dump() saves the updated data back to the file.