How to convert a json string to a dictionary in python

JSON stands for Javascript Object Notation in which the data is stored in an object format such as {x: 12, y: 24, z: 36}. The data stored inside JSON file is in the key-mapping format which is similar to the dictionary in python. This tutorial discusses how to convert a json string to dictionary in python.

JSON STRING TO DICTIONARY

Python has a built-in json library which has a load() function. The load function takes a json object as an input and convert it to dictionary.

First of all, import the json library. and then pass the json object to the load function.

import json

jsonData = '{"firstName": "Edward", "lastName": "John"}'

dictData= json.loads(jsonData)

print(dictData)

print(dictData['firstName'])

print(dictData['lastName'])
{'firstName': 'Edward', 'lastName': 'John'}
Edward
John

Similarly, you can also load a JSON file and convert the data stored in it to dictionary format. To load the JSON file, the syntax is as follow:

json.load(file_name)

In the follow example, we will convert a JSON file into a dictionary.

# importing the module
import json
 
# Opening JSON file
with open('data.json') as json_file:
    data = json.load(json_file)
    # Print the type of data variable
    print("Type:", type(data))
 
    # Print the data of dictionary
    print("\nData:", data['Info'])
Type <class 'dict'>
Data: [{'Name' : 'John', 'Roll No.' : '123456', 'University' : 'XYZ' },{'Name' : 'Jasmine' ,'Roll No.' : '4321','University' : 'MNG' }]

JSON NESTED OBJECT TO DICTIONARY

In the real-world applications, most of the data consists of nested objects. The JSON string consists of JSON object nested within another object consisting of data in the form of the name: value pairs. The code below parse the nested JSON object to Dictionary.

import json

jsonData = '{"firstName": "Edward", "lastName": "John", "coursesMarks":{"English":20,"Science":45, "Maths": 48}}'

dictData= json.loads(jsonData)

print(dictData)

print(dictData['coursesMarks'])

print(type(dictData))
{'firstName': 'Edward', 'lastName': 'John', 'coursesMarks': {'English': 20, 'Science': 45, 'Maths': 48}}
{'English': 20, 'Science': 45, 'Maths': 48}
<class 'dict'>

The datatype of this converted object is dictionary. In this way, you can convert a simple object or nested JSON objects into a python dictionary. For more tutorials, let us know in the comments.

Leave a Comment

Your email address will not be published. Required fields are marked *