How to Append Data to JSON array in Python
In this tutorial, you’ll learn various methods to append data to an existing JSON array in Python.
We’ll cover several examples, from appending to JSON array, appending dictionaries and lists as elements, appending to nested JSON objects, and handling JSON data stored in files.
Using append()
You can use the append method to append to a JSON array:
import json feedback_data = [ {"customer_id": 101, "feedback": "Great coverage"}, {"customer_id": 102, "feedback": "Fast internet"} ] new_feedback = {"customer_id": 103, "feedback": "Friendly customer service"} feedback_data.append(new_feedback) print(json.dumps(feedback_data, indent=4))
Output:
[ { "customer_id": 101, "feedback": "Great coverage" }, { "customer_id": 102, "feedback": "Fast internet" }, { "customer_id": 103, "feedback": "Friendly customer service" } ]
In this script, feedback_data
already contains two entries. Each entry is a dictionary with customer_id
and feedback
.
Appending Multiple Elements using extend()
Python extend()
method allows you to append multiple elements to a list in a single operation.
Now, suppose you receive a batch of new tower data that needs to be added to the existing array.
Instead of appending each item individually, you can use extend()
to add them all in one go.
import json tower_data = [ {"tower_id": 1001, "location": "Downtown"}, {"tower_id": 1002, "location": "Suburbs"} ] # Data to append new_towers = [ {"tower_id": 1003, "location": "Industrial Area"}, {"tower_id": 1004, "location": "Rural"} ] tower_data.extend(new_towers) print(json.dumps(tower_data, indent=4))
Output:
[ { "tower_id": 1001, "location": "Downtown" }, { "tower_id": 1002, "location": "Suburbs" }, { "tower_id": 1003, "location": "Industrial Area" }, { "tower_id": 1004, "location": "Rural" } ]
In this script, tower_data
is an array of dictionaries, each representing a telecom tower’s data. new_towers
is a list of new tower records.
This makes extend()
more efficient than append()
for adding multiple items, as it avoids the overhead of multiple method calls.
Appending to Nested Element
Here’s how to append to an existing plan’s tier list:
import json telecom_plans = [ { "plan_id": "PlanA", "tiers": [ {"tier_name": "Basic", "features": ["2GB Data", "100 Minutes"]}, {"tier_name": "Pro", "features": ["5GB Data", "500 Minutes"]} ] }, { "plan_id": "PlanB", "tiers": [ {"tier_name": "Standard", "features": ["10GB Data", "Unlimited Texts"]} ] } ] # New tier to append to PlanA new_tier = {"tier_name": "Advanced", "features": ["10GB Data", "Unlimited Calls"]} # Locate PlanA and append the new tier to its tiers for plan in telecom_plans: if plan["plan_id"] == "PlanA": plan["tiers"].append(new_tier) break print(json.dumps(telecom_plans, indent=4))
Output:
[ { "plan_id": "PlanA", "tiers": [ { "tier_name": "Basic", "features": ["2GB Data", "100 Minutes"] }, { "tier_name": "Pro", "features": ["5GB Data", "500 Minutes"] }, { "tier_name": "Advanced", "features": ["10GB Data", "Unlimited Calls"] } ] }, { "plan_id": "PlanB", "tiers": [ { "tier_name": "Standard", "features": ["10GB Data", "Unlimited Texts"] } ] } ]
In this script, we first identify the plan to which we want to add the new tier (in this case, “PlanA”).
We use a for
loop to iterate through the telecom_plans
array. When we find “PlanA”, we append the new_tier
to its tiers
list using the append()
method, which adds the new tier to the end of the existing tier list.
Appending to a JSON Array Loaded from a File
Let’s go through how to append new data to a JSON array that is loaded from a file:
- Read the JSON file: Load the existing JSON data into Python.
- Append the data: Append new elements to the loaded JSON array.
- Write back to the file: Save the updated array back to the JSON file.
First, assume we have a JSON file named telecom_data.json
with the following content:
[ { "user_id": 1001, "usage": "5GB" }, { "user_id": 1002, "usage": "10GB" } ]
Now, let’s append a new user’s data to this file:
import json file_path = 'telecom_data.json' with open(file_path, 'r') as file: data = json.load(file) new_user_data = {"user_id": 1003, "usage": "8GB"} data.append(new_user_data) with open(file_path, 'w') as file: json.dump(data, file, indent=4) print("New user data appended successfully.")
This script reads the existing JSON array from telecom_data.json
, appends the new_user_data
to this array, and then writes the updated array back to the same file.
The use of with open()
ensures that the file is properly closed after its contents are read and written.
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.