How To Get JSON Value by Key in Python

In this tutorial, we’ll explore various methods to retrieve values from JSON data using Python.

We’ll cover methods such as direct access and the get() method to more advanced methods like looping through JSON arrays and using dictionary comprehension.

 

 

Direct Access

Suppose you have a JSON object that includes various keys like customer_id, name, and subscription_plan.

You can access these values by key names directly:

import json
json_data = '{"customer_id": 12345, "name": "Jordan", "subscription_plan": "Premium"}'
data = json.loads(json_data)
customer_id = data["customer_id"]
customer_name = data["name"]
subscription_plan = data["subscription_plan"]
print("Customer ID:", customer_id)
print("Customer Name:", customer_name)
print("Subscription Plan:", subscription_plan)

Output:

Customer ID: 12345
Customer Name: Jordan
Subscription Plan: Premium

By converting the JSON string to a Python dictionary using json.loads(), you can retrieve any value by simply referencing its key.

 

Using get() Method

Using the get() method to access values provides a safer alternative to direct key access.

This method is useful in handling cases where a key might not exist in the JSON object, thus avoiding potential KeyError exceptions.

Suppose you need to access the email address of a customer, but not all customers might have an email address listed:

import json
json_data = '{"customer_id": 12345, "name": "Jordan", "subscription_plan": "Premium"}'
data = json.loads(json_data)
email_address = data.get("email", "No email provided")
print("Email Address:", email_address)

Output:

Email Address: No email provided

In this example, the get() method is used to attempt to retrieve the email key.

Since email is not present in our JSON data, the method returns the default value "No email provided".

 

Using a Loop

Iterating over JSON data using a loop is a powerful technique for processing multiple key-value pairs, especially in complex or nested JSON structures.

Imagine you have a JSON array containing multiple customer records. Each record includes keys like customer_id, name, and subscription_plan.

import json
json_data = '''
[
    {"customer_id": 12345, "name": "Jordan", "subscription_plan": "Premium"},
    {"customer_id": 12346, "name": "Alex", "subscription_plan": "Basic"},
    {"customer_id": 12347, "name": "Taylor", "subscription_plan": "Standard"}
]
'''
customers = json.loads(json_data)
for customer in customers:
    print("Customer ID:", customer["customer_id"])
    print("Name:", customer["name"])
    print("Subscription Plan:", customer["subscription_plan"])
    print()

Output:

Customer ID: 12345
Name: Jordan
Subscription Plan: Premium

Customer ID: 12346
Name: Alex
Subscription Plan: Basic

Customer ID: 12347
Name: Taylor
Subscription Plan: Standard

By looping through the array, you can access and manipulate each customer’s data individually.

 

Using Dictionary Comprehension

Suppose you want to create a new dictionary that maps customer IDs to their subscription plans. Here’s how you can do this using dictionary comprehension:

import json
json_data = '''
[
    {"customer_id": 12345, "name": "Jordan", "subscription_plan": "Premium"},
    {"customer_id": 12346, "name": "Alex", "subscription_plan": "Basic"},
    {"customer_id": 12347, "name": "Taylor", "subscription_plan": "Standard"}
]
'''
customers = json.loads(json_data)
customer_subscriptions = {customer["customer_id"]: customer["subscription_plan"] for customer in customers}
print(customer_subscriptions)

Output:

{12345: 'Premium', 12346: 'Basic', 12347: 'Standard'}

In this example, the dictionary comprehension iterates over each customer record, using the customer_id as the key and the subscription_plan as the value in the new dictionary.

 

Get Value by Key in Nested JSON

You can access a specific value within this nested structure by chaining key names:

import json
json_data = '''
{
    "customer": {
        "id": 12345,
        "name": "Jordan",
        "account_details": {
            "plan": "Premium",
            "billing": {
                "current_month": 100,
                "previous_month": 80
            }
        }
    }
}
'''
data = json.loads(json_data)
current_month_billing = data["customer"]["account_details"]["billing"]["current_month"]
print("Current Month Billing:", current_month_billing)

Output:

Current Month Billing: 100

In this code snippet, we navigate through the nested dictionaries to access the current_month billing amount.

Leave a Reply

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