AppDividend
Latest Code Tutorials

Python json to dict: Converting JSON to Dictionary

JSON stands for JavaScript Object Notation. It means that JSON is a script (executable) file, which is made of text in the programming language, is used to save and transfer the data. Python supports JSON through an inbuilt package called json package. Now let’s see how to convert json to python dict and string.

Python json to dict

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 a Python object. The json module makes it easy to parse json strings and files containing the json object.

You can parse the JSON string using json.loads() method. The json.loads() method returns the Dictionary. To work with JSON (string, or file containing the JSON object) in Python, you have to use Python’s json module.

You need to import json module before you can use it.

Steps to convert json to dict in Python

Step 1: Prepare json data

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

# app.py

import json

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

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

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

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

Now, to use this file inside the app.py file, we will use it Python with statement.

# app.py

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

Here, we have used the open() function to read a json file.

If you do not know how to read and write operations in Python, then check out the following articles.

  1. How to read a file in Python
  2. How to write a file in Python
  3. File handling in Python

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

Write the following code inside the app.py file.

# app.py

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.

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

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

# app.py

import json

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

print(data)
print(type(data))

print(data['games'])

Output

python3 app.py
{'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 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 just have json content as a string, then we have used 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"
    }
  ]
}

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

# app.py

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

python3 app.py
{'name': 'DualShock', 'price': '60'}

Printing nested dicitonary as a key-value pair

Name: DualShock
Price: 60

Name: DualSense
Price: 100

Conclusion

Python json module provides a function that helps us to convert Python JSON to Dictionary and Python Dictionary to JSON seamlessly. 

Python json.dumps() is a built-in function that converts a dictionary to string object, not the json(dictionary) object.

Python json.loads() is a built-in function that converts the json to dictionary object.

If you are working with a static file or server, you can easily convert data from each other.

That’s it for this tutorial.

See also

Python Dictionary to DataFrame

Python Dictionary to CSV

Python Dictionary to String

Leave A Reply

Your email address will not be published.

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