Convert a JSON String to a Dictionary in Python

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}. JSON strings are commonly used to represent structured data, such as API responses, configuration settings, etc. By converting the JSON string to a dictionary, you can easily extract specific values or retrieve the information you need from the JSON string. The data stored inside the JSON string is in the key-mapping format which is similar to the dictionary in Python. Converting a JSON string to a dictionary simplifies data handling and data manipulation. It provides an easy way to access and deal with the structured data contained in the JSON format. This tutorial discusses how to convert a JSON string to a dictionary in Python.

To convert a JSON string to a dictionary in Python, you can leverage the “JSON” module and its “loads()” function. By passing the JSON string as a parameter to the “loads()” function, Python will deserialize the string and transform it into a dictionary object. This allows for seamless data manipulation and modification.

Utilizing the “json” module’s “loads()” function ensures efficient conversion from JSON to a dictionary in Python.

JSON String to Dictionary Conversion in Python

Python has a built-in JSON library that has a load() function. The load function takes a JSON object as input and converts it to the 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 following 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' }]

Conversion of JSON Nested Object to Dictionary

In real-world applications, most of the data consists of nested objects. The JSON string consists of a JSON object nested within another object consisting of data in the form of the name: value pairs. The code below parses 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 a dictionary. In this way, you can convert a simple object or nested JSON object into a Python dictionary.

Dictionary to JSON String

Now, let’s see how we can convert a Python dictionary to a JSON format. The “json” module provides another function “dumps” which takes an object as an argument and returns a string.

In the example below, we will convert the Python dictionary created in the above example into a string in JSON format.

import json

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

# Get a JSON formatted string
output = json.dumps(jsonData)

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

In this way, we can represent the dictionary as a string in JSON format. You can check the data type of this variable by using the type function.

When working with structured data, converting a JSON string to a dictionary in Python is a common procedure. The procedure entails parsing the JSON string and converting it into a dictionary object, which enables simple data access and manipulation. Developers can use this conversion to extract specific values, modify the data structure, perform conditional checks, and seamlessly integrate JSON data with existing applications. The JSON module also includes error handling and validation techniques to assure the integrity and correctness of the JSON data during the conversion process. In this article, we have covered in detail how you can convert a string of a simple JSON object and nested objects to dictionaries and vice versa.

If you want to learn more about Python Programming, Visit Python Programming Tutorials

If you have any queries regarding this tutorial, let us know in the comments or contact us.

Leave a Comment

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