How to Extract Part of a JSON Object in Python?

Estimated read time 2 min read

You can extract a part of a JSON object in Python by navigating through the JSON structure and extracting the desired data using 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 part of JSON object
contact = data["contact"]

# Extract specific data from the extracted part
email = contact["email"]
phone = contact["phone"]

# Print extracted data
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 then use dictionary indexing to extract the nested part of the JSON object under the key “contact” into a new dictionary called contact. We can then use dictionary indexing or dot notation on the contact dictionary to extract the specific data we want, which in this case are the values for the keys “email” and “phone”.

Note that when extracting parts of a JSON object, you should handle exceptions appropriately to account for cases where the specified keys may not exist in the JSON data or the JSON data structure may not be as expected. 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