How to Extract Specific Data from JSON in Python?

Estimated read time 2 min read

You can extract specific data from a JSON object in Python using standard dictionary indexing or dot notation. Here’s an example:

import json

# Example JSON data
json_data = '''
{
    "name": "John",
    "age": 30,
    "city": "New York",
    "contact": {
        "email": "john@example.com",
        "phone": "123-456-7890"
    }
}
'''

# Parse JSON data
data = json.loads(json_data)

# Extract specific data using dictionary indexing or dot notation
name = data["name"]
age = data["age"]
city = data["city"]
email = data["contact"]["email"]
phone = data["contact"]["phone"]

# Print extracted data
print("Name:", name)
print("Age:", age)
print("City:", city)
print("Email:", email)
print("Phone:", phone)

In this example, we have an example JSON object represented as a string in json_data. We parse the JSON data using json.loads() to convert it into a Python dictionary. We can then extract specific data from the dictionary using dictionary indexing or dot notation. For example, we extract the values for the keys “name”, “age”, and “city” directly using dictionary indexing, and we extract the values for the nested keys “email” and “phone” using dot notation.

Note that when using dictionary indexing or dot notation to extract data from a JSON object, you should handle exceptions appropriately to account for cases where the specified keys may not exist in the JSON data. You can use techniques like dict.get() or dict.setdefault() to provide default values or handle missing keys gracefully. Additionally, it’s important to validate and sanitize any user-provided or untrusted JSON data to prevent security vulnerabilities such as JSON injection attacks.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply