How to convert JSON to a python dictionary

How to convert JSON to a python dictionary:

JSON or Javascript object notation is a lightweight format for exchanging and storing data. Python provides json module for working with JSON contents. It provides a method called loads() which can be used to convert JSON data to a python dictionary.

In this post, we will learn how to use loads() to convert JSON data from a string and from a file to a python dictionary.

Python json.loads(s):

loads() method is called to convert a string, byte-array or bytes to a JSON. For using this method, we need to import json module and use it to parse data.

For example:

import json

json_data = '{"1": "Jan", "2": "Feb", "3": "March", "4": "April"}'

json_dict = json.loads(json_data)

print(json_dict)
print(type(json_dict))

It will print:

{'1': 'Jan', '2': 'Feb', '3': 'March', '4': 'April'}
<class 'dict'>
  • json_data is a string holding a JSON string.
  • The first print statement printed the dictionary created by converting the json_data to the dictionary json_dict.
  • The second dictionary prints the type of the json_dict which is dict.

Loading data from a file:

We can also load the data from a JSON file and parse it to a dictionary. Create a file data.json with the below data:

{
  "1": "Jan",
  "2": "Feb",
  "3": "March",
  "4": "April"
}

The below code will read the data and parse it to a dict :

import json

with open("data.json") as f:
    json_dict = json.load(f)
    print(json_dict)
    print(type(json_dict))

Here,

  • We are opening the data.json file and loading the data using load().

It will print the below output:

{'1': 'Jan', '2': 'Feb', '3': 'March', '4': 'April'}
<class 'dict'>

You might also like: