How to Convert JSON to Dictionary in Python

To convert json to dict in Python, use the json.load() function. The json.load() is a built-in function that deserializes json data to an object and returns the Dictionary.

Steps to convert json to dict in Python

Step 1: Prepare json data

Create an app.py file and see the following code.

import json

videogame = '{"console": "Playstation 5", "games": ["Spiderman", "God of War"]}'

If you don’t want to write the hardcode json data, you can use an external json file.

Let’s say we have an external json file called data.json, and the file’s content is as follows.

{
  "console": "Playstation 5",
  "games": [
  "Spiderman",
  "God of War"
 ]
}

We will use Python with statement to use this file inside the app.py file.

import json

with open('data.json') as d:
  print(d)

We have used the open() function to read a json file.

Step 2: Convert JSON to dict using json.load() function

Write the following code inside the app.py file.

import json


with open('data.json') as d:
  dictData = json.load(d)
  print(dictData)
  print(type(dictData))
  print(dictData['games'])

In the above code, after converting json to dict, we have printed that Dictionary, its type, and its one property.

See the output.

{'console': 'Playstation 5', 'games': ['Spiderman', 'God of War']}
<class 'dict'>
['Spiderman', 'God of War']

If you don’t want to read a file and use the hardcoded json data in the file, then you can write the following code.

import json

videogame = '{"console": "Playstation 5", "games": ["Spiderman", "God of War"]}'
data = json.loads(videogame)

print(data)
print(type(data))

print(data['games'])

Output

{'console': 'Playstation 5', 'games': ['Spiderman', 'God of War']}
<class 'dict'>
['Spiderman', 'God of War']

The output is the same, but there is one major difference in json functions.

In this case, we have used json.loads() function and not json.load() function.

Let’s see what the difference between them is.

Difference between json.load() and json.loads()

Python json.load() function must be used with a file object and json.loads() function is used with json string. The “s” stands for a string in the loads() function name.

The json.loads() function does not take a file path but takes the file contents as a string.

So, in the above examples, when we have a file path of data.json, we have used json.load() function, and when we have json content as a string, use json.loads() function.

Here’s the table showing Python objects and their equivalent conversion to json.

Python JSON Equivalent
dict object
list, tuple array
str string
int, float, int number
True true
False false
None null

How to convert nested JSON object to Dictionary

To convert a nested json object to a dictionary in Python, use the json.load() method with for loop. Let’s say we have the following content inside the data.json file.

{
  "console": "Playstation 5",
  "games": ["Spiderman", "God of War"],
  "controller": [
  {
    "name": "DualShock",
    "price": "60"
  },
  {
    "name": "DualSense",
    "price": "100"
  }
 ]
}

We will use with open() function to open the json file, convert the file object to a Dictionary and print the content of the Dictionary. Write the following code inside the app.py file.

import json

# Opening JSON file
with open('data.json') as json_file:
 data = json.load(json_file)

 # for reading nested data [0] represents
 # the index value of the list
 print(data['controller'][0])

 print("\nPrinting nested dicitonary as a key-value pair\n")
 for i in data['controller']:
 print("Name:", i['name'])
 print("Price:", i['price'])

Output

{'name': 'DualShock', 'price': '60'}

Printing nested dicitonary as a key-value pair

Name: DualShock
Price: 60

Name: DualSense
Price: 100

FAQ

How to convert a Python dict to a JSON string?

You can use the json.dumps() function that takes a Python dict object and returns a JSON-formatted string. The syntax of json.dumps() method is: json.dumps(data).

import json

data = {"name": "Krunal", "hobby": "dance", "rank": 19}
json_string = json.dumps(data)
print(json_string)

Output

{"name": "Krunal", "hobby": "dance", "rank": 19}

How to convert a JSON string to a Python dictionary?

You can use the json.loads() function in Python to convert a JSON string to a Python dictionary

import json

json_string = '{"name": "Krunal", "hobby": "dance", "rank": 19}'
dict = json.loads(json_string)
print(dict)

Output

{'name': 'Krunal', 'hobby': 'dance', 'rank': 19}

What happens if the JSON string is invalid while converting json to dict?

If the JSON string is invalid, the json.loads() function will raise a json.JSONDecodeError exception or  SyntaxError exception.

import json

json_string = '{"name": "Krunal", "hobby": "dance", "rank" 19}'

try:
  dict = json.loads(json_string)
except json.JSONDecodeError as e:
  print(f"Error: {e}")

Output

Error: Expecting ':' delimiter: line 1 column 45 (char 44)

Can I specify options when converting JSON to a dict?

No, there are no options available for json.loads() function to customize the conversion of a JSON string to a Python dictionary. It returns the dictionary representation of the JSON data.

That’s it.

Related posts

Python dict to json

Parse json in Python

Leave a Comment

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