How to Convert JSON to Dictionary in Python

Here are 2 ways to convert json to dictionary in Python: 

  1. Using json.loads()
  2. 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

Visual Representation of Convert JSON-formatted string to Dictionary

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

Visual Representation of Using json.load()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.

Nested 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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.