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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.