How to convert JSON data into a Python object with example?

You can convert JSON data into a Python object using the json module in Python. The json module provides methods for both encoding (converting Python objects to JSON) and decoding (converting JSON to Python objects). Here’s how you can convert JSON data into a Python object with an example:

Assuming you have a JSON string, you can use the json.loads() function to convert it into a Python object. Here’s an example:

import json

# Sample JSON data as a string
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# Convert JSON data to a Python dictionary
python_obj = json.loads(json_data)

# Access the Python object's attributes
print("Name:", python_obj['name'])
print("Age:", python_obj['age'])
print("City:", python_obj['city'])

In this example, the json.loads() function is used to convert the JSON string json_data into a Python dictionary named python_obj. You can then access the attributes of the Python object using dictionary keys.

Keep in mind that json.loads() works with valid JSON strings. If you have JSON data in a file, you can use the json.load() function to read and parse the JSON directly from the file:

import json

# Read JSON data from a file and convert to Python object
with open('data.json') as json_file:
python_obj = json.load(json_file)

print(python_obj) # Print the Python object

Replace 'data.json' with the path to your JSON file.

The json module can handle more complex JSON structures as well, including nested dictionaries and lists.