How To Add JSON Keys Based on Conditions in Python
In this tutorial, you’ll learn how to add JSON keys based on various conditions.
From adding keys to JSON objects based on simple conditions, checking for existing keys, handling null values, working with nested structures, and much more.
Add Key If Not Exist
Let’s say you want to add a new key account_status
to each customer record.
However, this key should only be added if it doesn’t already exist in the record.
Here’s how you can do this:
import json customer_data = [ {"id": 1, "name": "Customer A", "monthly_usage": 450}, {"id": 2, "name": "Customer B", "monthly_usage": 1200}, {"id": 3, "name": "Customer C", "monthly_usage": 300} ] for customer in customer_data: if 'account_status' not in customer: customer['account_status'] = 'Active' updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "id": 1, "name": "Customer A", "monthly_usage": 450, "eligible_for_offer": false, "account_status": "Active" }, { "id": 2, "name": "Customer B", "monthly_usage": 1200, "eligible_for_offer": true, "account_status": "Active" }, { "id": 3, "name": "Customer C", "monthly_usage": 300, "eligible_for_offer": false, "account_status": "Active" } ]
In this snippet, the if 'account_status' not in customer
condition checks each customer record to see if the account_status
key exists. If it doesn’t, the key is added with a value of 'Active'
.
Add Key If Value Is Empty
Imagine some customer records have an email
field, but it might be empty for some customers.
You want to add a key contact_update_required
set to True
if the email
field is empty.
Here’s how you can do this:
import json customer_data = [ {"id": 1, "name": "Customer A", "email": "customer.a@email.com"}, {"id": 2, "name": "Customer B", "email": ""}, {"id": 3, "name": "Customer C", "email": "customer.c@email.com"} ] for customer in customer_data: if not customer.get('email'): customer['contact_update_required'] = True updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "id": 1, "name": "Customer A", "email": "customer.a@email.com" }, { "id": 2, "name": "Customer B", "email": "", "contact_update_required": true }, { "id": 3, "name": "Customer C", "email": "customer.c@email.com" } ]
In this code, we check if the email
field is empty using if not customer.get('email')
.
This condition evaluates to True
if the email
field is either empty or non-existent.
If this condition is met, the contact_update_required
key is added with a value of True
.
Add Key at Specific Position
Let’s say you now want to add a new key region
to each customer record. However, you want this key at the beginning of each dictionary.
Here’s how you can accomplish this:
new_key_value = {"region": "Unknown"} for i, customer in enumerate(customer_data): customer_data[i] = {**new_key_value, **customer} updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "region": "Unknown", "id": 1, "name": "Customer A", "email": "customer.a@email.com" }, { "region": "Unknown", "id": 2, "name": "Customer B", "email": "", "contact_update_required": true }, { "region": "Unknown", "id": 3, "name": "Customer C", "email": "customer.c@email.com" } ]
In this snippet, {**new_key_value, **customer}
uses dictionary unpacking to create a new dictionary with region
at the beginning, followed by the existing key-value pairs from customer
.
The original dictionaries in customer_data
are updated with these new dictionaries.
Add Key Based on Previous Value
Imagine you want to add a key data_plan_category
based on the value of the monthly_usage
.
For instance, if a customer’s monthly_usage
exceeds a certain threshold, they might be categorized differently.
Here’s an example of how to do this:
usage_thresholds = { "Basic": 500, "Premium": 1000, "Unlimited": 1500 } def determine_plan_category(usage): if usage <= usage_thresholds["Basic"]: return "Basic" elif usage <= usage_thresholds["Premium"]: return "Premium" else: return "Unlimited" for customer in customer_data: customer['data_plan_category'] = determine_plan_category(customer['monthly_usage']) updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "region": "Unknown", "id": 1, "name": "Customer A", "monthly_usage": 450, "account_status": "Active", "data_plan_category": "Basic" }, { "region": "Unknown", "id": 2, "name": "Customer B", "monthly_usage": 1200, "account_status": "Active", "data_plan_category": "Unlimited" }, { "region": "Unknown", "id": 3, "name": "Customer C", "monthly_usage": 300, "account_status": "Active", "data_plan_category": "Basic" } ]
In this example, the determine_plan_category
function decides the category based on the monthly_usage
value.
Adding Keys in the Presence of Null Values
Imagine some records have a key last_contact_date
that could be null.
You want to add a key requires_follow_up
set to True
if last_contact_date
is null.
Here’s how to do it:
customer_data = [ {"id": 1, "name": "Customer A", "last_contact_date": "2021-05-01"}, {"id": 2, "name": "Customer B", "last_contact_date": None}, {"id": 3, "name": "Customer C", "last_contact_date": "2021-07-15"} ] for customer in customer_data: if customer.get('last_contact_date') is None: customer['requires_follow_up'] = True updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "id": 1, "name": "Customer A", "last_contact_date": "2021-05-01" }, { "id": 2, "name": "Customer B", "last_contact_date": null, "requires_follow_up": true }, { "id": 3, "name": "Customer C", "last_contact_date": "2021-07-15" } ]
In this code, the condition if customer.get('last_contact_date') is None
checks if the last_contact_date
is null. If it is, the new key requires_follow_up
is set to True
.
Adding Keys Based on Multiple Conditions
Suppose you want to add a key service_upgrade_needed
based on multiple conditions: if the customer’s monthly_usage
is high and their account_status
is active, but they have an old device_model
.
Here’s how to do that:
import json customer_data = [ {"id": 1, "name": "Customer A", "monthly_usage": 450, "account_status": "Active", "device_model": "Model X"}, {"id": 2, "name": "Customer B", "monthly_usage": 1200, "account_status": "Inactive", "device_model": "Model Y"}, {"id": 3, "name": "Customer C", "monthly_usage": 1500, "account_status": "Active", "device_model": "Model X"} ] older_models = ["Model X", "Model Z"] for customer in customer_data: if (customer['monthly_usage'] > 1000 and customer['account_status'] == "Active" and customer['device_model'] in older_models): customer['service_upgrade_needed'] = True updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "id": 1, "name": "Customer A", "monthly_usage": 450, "account_status": "Active", "device_model": "Model X" }, { "id": 2, "name": "Customer B", "monthly_usage": 1200, "account_status": "Inactive", "device_model": "Model Y" }, { "id": 3, "name": "Customer C", "monthly_usage": 1500, "account_status": "Active", "device_model": "Model X", "service_upgrade_needed": true } ]
In this code, the combination of conditions checks if a customer’s monthly usage exceeds 1000, if their account is active, and if they are using an older device model.
If all these conditions are met, the service_upgrade_needed
key is set to True
.
Add Nested Key Based on Parent Key
Assume now that each customer record includes a nested object subscription_details
, containing keys like plan_type
and expiry_date
.
You want to add a new key renewal_reminder
within this nested object if the expiry_date
is approaching.
Here’s how to do this:
import json from datetime import datetime customer_data = [ {"id": 1, "name": "Customer A", "subscription_details": {"plan_type": "Standard", "expiry_date": "2023-01-15"}}, {"id": 2, "name": "Customer B", "subscription_details": {"plan_type": "Premium", "expiry_date": "2023-01-10"}}, {"id": 3, "name": "Customer C", "subscription_details": {"plan_type": "Basic", "expiry_date": "2023-02-01"}} ] # Function to check if renewal reminder is needed def needs_renewal_reminder(expiry_date_str): expiry_date = datetime.strptime(expiry_date_str, "%Y-%m-%d") today = datetime.now() return (expiry_date - today).days <= 30 # Add 'renewal_reminder' in nested 'subscription_details' for customer in customer_data: expiry_date = customer["subscription_details"]["expiry_date"] if needs_renewal_reminder(expiry_date): customer["subscription_details"]["renewal_reminder"] = True updated_data_json = json.dumps(customer_data, indent=4) print(updated_data_json)
Output:
[ { "id": 1, "name": "Customer A", "subscription_details": { "plan_type": "Standard", "expiry_date": "2023-01-15", "renewal_reminder": true } }, { "id": 2, "name": "Customer B", "subscription_details": { "plan_type": "Premium", "expiry_date": "2023-01-10", "renewal_reminder": true } }, { "id": 3, "name": "Customer C", "subscription_details": { "plan_type": "Basic", "expiry_date": "2023-02-01" } } ]
In this code, the needs_renewal_reminder
function calculates if the subscription expiry date is within the next 30 days.
For each customer, if this condition is met, the key renewal_reminder
is added to the subscription_details
nested object.
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.