Here are 2 ways to convert json to dictionary in Python:
- Using json.loads()
- Using json.load()
Method 1: Using json.loads()
The json.loads() function from json module takes a JSON-formatted string and converts it into dictionary.
Visual Representation
Example 1: Basic Conversation
import json
# JSON-formatted string
json_string = '{"student_name": "Smith", "age": 15, "country": "USA"}'
# Convert JSON string to dictionary
dict = json.loads(json_string)
print(dict)
print(type(dict))
Output
{'student_name': 'Smith', 'age': 15, 'country': 'USA'}
<class 'dict'>
Example 2: Nested JSON string
import json
json_string = '{"student_name": "Smith", "personal_info": {"age": 15, "country": "USA"}}'
dict = json.loads(json_string)
print(dict)
print(type(dict))
Output
{'student_name': 'Smith', 'personal_info': {'age': 15, 'country': 'USA'}}
<class 'dict'>
Method 2: Using json.load()
The json.load() method is used for reading JSON data directly from a file.
Visual Representation
Example
import json
# Open the JSON file for reading
with open('data.json') as file:
# Use json.load() to read the file and convert it to a dictionary
dict = json.load(file)
print(dict)
print(type(dict))
Output
{'student_name': 'Smith', 'age': 15, 'country': 'USA'}
<class 'dict'>
Example 2: Nested JSON File
Below is the nested_data.json file.
import json
with open('nested_data.json') as file:
dict = json.load(file)
print(dict)
print(type(dict))
Output
{'student_name': 'Smith', 'personal_info': {'age': 15, 'country': 'USA'}}
<class 'dict'>
That’s it.