How To Replace JSON Value by Key in Python

In this tutorial, you’ll learn different techniques to replace a value by key in a JSON object using Python.

We will explore various methods such as direct replacement, using the dict.update() method, using recursive functions for nested JSON, JSONPath for complex data structures, and using loops and dictionary comprehension for bulk updates.

 

 

Direct Replacement

First, let’s assume you have a JSON object like this:

customer_data = {
    "customer_id": 12345,
    "name": "Jordan",
    "plan": "Basic",
    "last_payment": 50
}

To replace the value of the key plan, you can use direct assignment:

customer_data['plan'] = 'Premium'
print(customer_data)

Output:

{
    "customer_id": 12345,
    "name": "Jordan",
    "plan": "Premium",
    "last_payment": 50
}

The output shows that the value of the key plan has been successfully changed from “Basic” to “Premium”.

 

Replace Multiple Values Using dict.update()

You can use dict.update() to update multiple values at once.

Suppose you want to update both the plan and last_payment values for a customer. Here’s how you can do it using dict.update():

updates = {
    "plan": "Unlimited",
    "last_payment": 75
}
customer_data.update(updates)
print(customer_data)

Output:

{
    "customer_id": 12345,
    "name": "Jordan",
    "plan": "Unlimited",
    "last_payment": 75
}

The output confirms that both the plan and last_payment values have been updated.

 

Replace Nested JSON Using Recursive Function

Sometimes, you might encounter nested JSON objects, where a direct replacement or dict.update() won’t suffice.

The recursive function searches through all levels of the nested JSON object to find and replace the value by key.

customer_data = {
    "customer_id": 12345,
    "name": "Jordan",
    "account_details": {
        "plan": "Basic",
        "features": {
            "international_calls": False,
            "data_rollover": True
        }
    }
}

Let’s update the international_calls using recursive function:

def update_nested_json(obj, key, new_value):
    if key in obj:
        obj[key] = new_value
    for k, v in obj.items():
        if isinstance(v, dict):
            update_nested_json(v, key, new_value)
update_nested_json(customer_data, 'international_calls', True)
print(customer_data)

Output:

{
    "customer_id": 12345,
    "name": "Jordan",
    "account_details": {
        "plan": "Basic",
        "features": {
            "international_calls": True,
            "data_rollover": True
        }
    }
}

The output indicates that the international_calls feature within the nested features dictionary has been successfully updated to True.

 

Using JSONPath

JSONPath is a query language for JSON, similar to XPath for XML. It’s used for selecting and extracting data from a JSON document.

While Python doesn’t have built-in support for JSONPath, you can use external libraries like jsonpath-ng to use this powerful language.

First, you need to install the jsonpath-ng package. You can do this using pip:

pip install jsonpath-ng

Now, let’s use JSONPath to update a value in the customer data. Suppose you want to update the plan in the customer’s account_details:

from jsonpath_ng import parse
import json
customer_data = json.loads("""
{
  "customer_id": 12345,
  "name": "Jordan",
  "account_details": {
    "plan": "Basic", 
    "features": {
      "international_calls": false,
      "data_rollover": true
    }
  }
}
""")

# Define the JSONPath expression
jsonpath_expr = parse('$.account_details.plan')

# Find the node and update it
for match in jsonpath_expr.find(customer_data):
    parent = match.context.value
    parent['plan'] = 'Unlimited'
updated_json = json.dumps(customer_data, indent=4)
print(updated_json)

Output:

{
    "customer_id": 12345,
    "name": "Jordan",
    "account_details": {
        "plan": "Unlimited",
        "features": {
            "international_calls": false,
            "data_rollover": true
        }
    }
}

The output shows that the plan within account_details has been changed to “Unlimited”.

 

Using For Loop

When dealing with JSON objects, especially those without deeply nested structures, a simple for loop can be an effective way to update values.

Suppose you want to update the last_payment value for all customers in a list of JSON objects.

customers_data = [
    {"customer_id": 12345, "name": "Jordan", "plan": "Basic", "last_payment": 50},
    {"customer_id": 12346, "name": "Alex", "plan": "Premium", "last_payment": 80},
    {"customer_id": 12347, "name": "Casey", "plan": "Standard", "last_payment": 60}
]

You can use a for loop to update the last_payment for each customer:

new_payment = 100
for customer in customers_data:
    customer['last_payment'] = new_payment
for customer in customers_data:
    print(customer)

Output:

{"customer_id": 12345, "name": "Jordan", "plan": "Basic", "last_payment": 100}
{"customer_id": 12346, "name": "Alex", "plan": "Premium", "last_payment": 100}
{"customer_id": 12347, "name": "Casey", "plan": "Standard", "last_payment": 100}

The output shows that the last_payment value for each customer in the list has been updated to 100.

 

Using Dictionary Comprehension

Dictionary comprehension is useful when you need to apply a transformation to all elements in a dictionary or a collection of dictionaries such as a JSON object.

Let’s say you need to update a specific value in several JSON objects contained within a list.

For example, you might want to increase the last_payment value by a certain percentage for all customers.

customers_data = [
    {"customer_id": 12345, "name": "Jordan", "plan": "Basic", "last_payment": 50},
    {"customer_id": 12346, "name": "Alex", "plan": "Premium", "last_payment": 80},
    {"customer_id": 12347, "name": "Casey", "plan": "Standard", "last_payment": 60}
]

To increase each customer’s last_payment by 20%, use dictionary comprehension:

increase_percentage = 20
updated_customers_data = [
    {k: (v * (1 + increase_percentage / 100)) if k == 'last_payment' else v for k, v in customer.items()}
    for customer in customers_data
]
for customer in updated_customers_data:
    print(customer)

Output:

{"customer_id": 12345, "name": "Jordan", "plan": "Basic", "last_payment": 60.0}
{"customer_id": 12346, "name": "Alex", "plan": "Premium", "last_payment": 96.0}
{"customer_id": 12347, "name": "Casey", "plan": "Standard", "last_payment": 72.0}

The output demonstrates that the last_payment for each customer has been increased by 20%.

Leave a Reply

Your email address will not be published. Required fields are marked *