The Wayback Machine - https://web.archive.org/web/20241125000124/https://www.geeksforgeeks.org/convert-json-to-dictionary-in-python/
Open In App

Convert JSON to dictionary in Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON stands for JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the Python JSON package into Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.

Function Used

json.load(): json.load() function is present in Python built-in ‘JSON’ module. This function is used to parse the JSON string.

json.loads(): json.loads() function is present in Python built-in ‘json’ module. This function is used to parse the JSON string.

Convert JSON String to Dictionary Python

In this example, we are going to convert a JSON string to Python Dictionary using json.loads() method of JSON module in Python. Firstly, we import json module and then define JSON string after that converting JSON string to Python dictionary by passing it to json.loads() in parameter. We have print the dictionary and their values using the keys as seen in the output.

Python
# Import JSON module
import json

# Define JSON string
jsonString = '{ "id": 121, "name": "Naveen", "course": "MERN Stack"}'

# Convert JSON String to Python
student_details = json.loads(jsonString)

# Print Dictionary
print(student_details)

# Print values using keys
print(student_details['name'])
print(student_details['course'])

Output
{'id': 121, 'name': 'Naveen', 'course': 'MERN Stack'}
Naveen
MERN Stack

Convert JSON File to Python Object

Below is the JSON file that we will convert to Python dictionary using json.load() mehtod.

python-json

In the below code, firstly we open the “data.json” file using file handling in Python and then convert the file to Python object using the json.load() method we have also print the type of data after conversion and print the dictionary.

Python
# Python program to demonstrate
# Conversion of JSON data to
# 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("\nPeople1:", data['people1'])
    print("\nPeople2:", data['people2'])

Output :

python-json

Convert Nested JSON Object to Dictionary

In this example, we will convert the nested JSON into a Python dictionary. For JSON data we will use the same JSON file used in the above example.

Python
# importing the module
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['people1'][0])
    
    # for printing the key-value pair of
    # nested dictionary for loop can be used
    print("\nPrinting nested dictionary as a key-value pair\n")
    for i in data['people1']:
        print("Name:", i['name'])
        print("Website:", i['website'])
        print("From:", i['from'])
        print()

Output :

python-json

Convert JSON String to Dictionary in Python

In this example, we will convert the json string into Python dictionary using json.loads() method. Firstly, we will import JSON module. Create a json string and store it in a variable ‘json_string’ after that we will convert the json string into dictionary by passing ‘json_string’ into json.loads() as argument and store the converted dictionary in ‘json_dict’. Finally, print the Python dictionary.

Python
import json

# JSON string
json_string = '{"Name": "Suezen", "age": 23, "Course": "DSA"}'

# Convert JSON string to dictionary
json_dict = json.loads(json_string)

print(json_dict)

Output
{'Name': 'Suezen', 'age': 23, 'Course': 'DSA'}

Convert JSON to dictionary in Python – FAQs

How to parse JSON into Python object?

You can parse JSON data into a Python object (typically a dictionary or list) using the json.loads() function.

import json

json_str = '{"name": "John", "age": 30, "city": "New York"}'
python_obj = json.loads(json_str)

print(python_obj)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

How to convert JSON text to dictionary in Python?

JSON text can be converted to a dictionary using the json.loads() function as shown in the previous example.

import json

json_text = '{"name": "Alice", "age": 25}'
dictionary = json.loads(json_text)

print(dictionary)
# Output: {'name': 'Alice', 'age': 25}

How to extract JSON data in Python?

To extract data from a JSON string, parse it into a Python object (dictionary or list) using json.loads() and then access the specific data using standard dictionary or list operations.

import json

json_data = '{"name": "Bob", "age": 35, "city": "Chicago"}'
data = json.loads(json_data)

name = data['name']
age = data['age']

print(f"Name: {name}, Age: {age}")
# Output: Name: Bob, Age: 35

How to convert JSON to readable format in Python?

To convert JSON data to a more readable format in Python, you can use the json.dumps() function with the indent parameter.

import json

json_data = '{"name": "Eve", "age": 28, "city": "Seattle"}'
python_obj = json.loads(json_data)

formatted_json = json.dumps(python_obj, indent=4)
print(formatted_json)

This will produce:

{
"name": "Eve",
"age": 28,
"city": "Seattle"
}

How to convert JSON string to dictionary in Python?

You can convert a JSON string directly into a dictionary using json.loads().

import json

json_str = '{"key1": "value1", "key2": "value2"}'
dictionary = json.loads(json_str)

print(dictionary)
# Output: {'key1': 'value1', 'key2': 'value2'}


Previous Article
Next Article

Similar Reads

How To Convert Python Dictionary To JSON?
JSON stands for JavaScript Object Notation. It means that a script (executable) file made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-string which conta
7 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
Difference between Json and Dictionary in Python
In Python, dictionaries and JSON (JavaScript Object Notation) both facilitate structured data representation, yet they diverge in usage and syntax. In this article, we will discuss the Definition of JSON and Dictionary and the difference between JSON and Dictionary in Python. JSON vs DictionaryDictionaries, native to Python, are employed for in-mem
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Psycopg2 - Insert dictionary as JSON
In this article, we are going to see how to insert a dictionary as JSON using Psycopg2 and Python. Python dict objects can be or rather should be stored in database tables as JSON datatype. Since most of the SQL databases have a JSON datatype. This allows using these objects or key-value pairs in the front-end or in an API to process the request th
4 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Convert Text file to JSON in Python
JSON (JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modul
4 min read
Convert JSON data Into a Custom Python Object
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(),
2 min read
Convert multiple JSON files to CSV Python
In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms : JSON File: A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data bet
8 min read
Convert class object to JSON in Python
Conversion of the class object to JSON is done using json package in Python. json.dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes. Object is first converted into dictionary format using __dict__ attribute.This newly created dictionary is pas
2 min read
Convert HTML source code to JSON Object using Python
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. We will use xmltojson mo
3 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
Python - Convert list of dictionaries to JSON
In this article, we will discuss how to convert a list of dictionaries to JSON in Python. Python Convert List of Dictionaries to JsonBelow are the ways by which we can convert a list of dictionaries to JSON in Python: Using json.dumps()Using json.dump()Using json.JSONEncoderUsing default ParameterDictionaries to JSON in Python Using json.dumps()In
5 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different methods, each offering its own advantages in differen
3 min read
Convert Generator Object To JSON In Python
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we'll explore some commonly used methods. Convert Generator Object To JSON In PythonBelo
2 min read
Convert a Bytes Array into Json Format in Python
In Python, dealing with bytes data is common, and converting a bytes array to JSON format is a frequent task. In this article, we will see how to convert a bytes array into JSON format in Python. Python Convert a Bytes Array into JSON FormatBelow are some of the ways by which we can convert a bytes array into JSON format in Python: Using decode and
3 min read
How to Convert JSON to Excel in Python
JSON (JavaScript Object Notation) is a widely used data format that is both easy to read and write for humans and simple for machines to parse and generate. However, there may be times when we need to convert this JSON data into an Excel spreadsheet for analysis or reporting. In this article, we'll explore how to import JSON data into Excel using P
3 min read
Convert CSV to JSON using Python
CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature v
2 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Convert dictionary object into string
The dictionary is an important container and is used almost in every code of day-to-day programming as well as web development with Python. The more it is used, the more is the requirement to master it and hence it's necessary to learn about them. Input: { "testname" : "akshat","test2name" : "manjeet","test3name" : "nikhil"}Output: {"testname": "ak
3 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition. Below are some ways to achieve the above task. I
8 min read
Convert nested Python dictionary to object
Let us see how to convert a given nested dictionary into an object Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method. C/C++ Code # importing the module import json # declaringa a class class obj: # constructor def __init__(self, dict1): self.__
2 min read
Different ways to convert a Python dictionary to a NumPy array
In this article, we will see Different ways to convert a python dictionary into a Numpy array using NumPy library. It’s sometimes required to convert a dictionary in Python into a NumPy array and Python provides an efficient method to perform this operation. Converting a dictionary to NumPy array results in an array holding the key-value pairs of t
3 min read
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers giving the size of the array along each dimension is k
3 min read
Convert PySpark DataFrame to Dictionary in Python
In this article, we are going to see how to convert the PySpark data frame to the dictionary, where keys are column names and values are column values. Before starting, we will create a sample Dataframe: C/C++ Code # Importing necessary libraries from pyspark.sql import SparkSession # Create a spark session spark = SparkSession.builder.appName('DF_
3 min read
Convert Python Dictionary List to PySpark DataFrame
In this article, we will discuss how to convert Python Dictionary List to Pyspark DataFrame. It can be done in these ways: Using Infer schema.Using Explicit schemaUsing SQL Expression Method 1: Infer schema from the dictionary We will pass the dictionary directly to the createDataFrame() method. Syntax: spark.createDataFrame(data) Example: Python c
3 min read
How to convert a MultiDict to nested dictionary using Python
A MultiDict is a dictionary-like object that holds multiple values for the same key, making it a useful data structure for processing forms and query strings. It is a subclass of the Python built-in dictionary and behaves similarly. In some use cases, we may need to convert a MultiDict to a nested dictionary, where each key corresponds to a diction
3 min read
Python - Convert Lists to Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to convert lists to nestings, i.e. each list value represents a new nested level. This kind of problem can have applications in many domains including web development. Let's discuss the certain way in which this task can be performed. Convert Lists to Nested D
5 min read
Practice Tags :
three90RightbarBannerImg