Open In App
Related Articles

How To Convert Python Dictionary To JSON?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 contains a value in key-value mapping within {}. It is similar to the dictionary in Python.

Note: For more information, refer to Read, Write, and Parse JSON using Python

Methods used to Convert Python to JSON and Writing JSON 

  • Using dump() function
  • Using dumps() function
  • Difference Between Dictionary and JSON

Convert Dictionary Python to JSON File using json.dump()

In this program, we are going to convert the Python dictionary to a JSON object and then stored it in a file. Firstly we import the JSON module and then define a dictionary that stored student details. Now, we are going to use json.dump() method to convert and write the JSON object to a file along with open() method of file handling in Python. We open the sample.json file in writing mode and after that, we write the file using json.dump() method of JSON module in Python.

Python3

import json
    
# Define student_details dictionary
student_details ={
    "name" : "sathiyajith",
    "rollno" : 56,
    "cgpa" : 8.6,
    "phonenumber" : "9976770500"
}
    
# Convert and write JSON object to file
with open("sample.json", "w") as outfile:
    json.dump(student_details, outfile)

                    

Output:

Convert Python to JSON object Using dumps() function

In the below code, we are going to convert a Python dictionary to a JSON object using json.dumps() method of JSON module in Python. Firstly, we import the JSON module and then define a dictionary that stores employee details. After that, we convert the ’employee_details’ dictionary to JSON object using json.dumps() method and stored into the variable ‘json_object’.

Python3

# import json module
import json 
      
# define Python dictionary
employee_details =
  "id": "04"
  "name": "sunil"
  "department": "HR"
      
# Convert Python to JSON 
json_object = json.dumps(employee_details, indent = 4)
 
# Print JSON object
print(json_object)

                    

Output
{
    "id": "04",
    "name": "sunil",
    "department": "HR"
}

Converting Nested Dictionary to JSON in Python

In the below code, we will convert the nested dictionary to JSON in Python. Firstly, we import JSON module and then create a nested dictionary. After that we convert the nested dictionary to JSON using json.dumps() method by passing dictionary ‘person’ and ‘indent=4’ as argument in it. Finally, we print the converted JSON.

Python3

import json
 
# Create a nested dictionary
person = {
    "name": "John Doe",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA"
    }
}
 
# Convert person dictionary to JSON
json_string = json.dumps(person, indent=4
print(json_string)

                    

Output
{
    "name": "John Doe",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA"
    }
}

Convert Dictionary to JSON Quotes

The below code will convert a Python dictionary to a JSON string with double quotes around the keys and values, we can achieve this using the json.dumps() function with the ensure_ascii parameter set to ‘False’.

Python3

import json
 
# Create a dictionary
data = {
    "name": "Krishna",
    "age": 30,
    "city": "Mathura"
}
 
# Convert the dictionary to a
# JSON string with double quotes
json_string = json.dumps(data,
                         ensure_ascii=False)
 
print(json_string)

                    

Output
{"name": "Krishna", "age": 30, "city": "Mathura"}

Convert Dictionary to JSON Array in Python

In the below code, we will convert the Python dictionary to JSON array. First, we create a sample dictionary ‘data’ and then create a list of dictionary using list comprehension to iterate over the keys of the dictionary and store it in a variable ‘array’. After that convert the array to JSON array using json.dumps() function and then print the JSON array.

Python3

import json
 
# Create a dictionary
data = {
    "name": "Krishna",
    "Course": "DSA",
    "Batch": "July_2023"
}
 
array = [{i: data[i]} for i in data]
 
# Convert the dictionary into a JSON array
json_array = json.dumps(array)
 
print(json_array)

                    

Output
[{"name": "Krishna"}, {"Course": "DSA"}, {"Batch": "July_2023"}]

Convert Dictionary to JSON using sort_keys in Python

In the below code, we will convert the Python dictionary using while sorting the keys. To convert a Python dictionary to a JSON string with sorted keys we have to specify the ‘sort_keys’ parameter as ‘True’ in json.dumps() function. We can see in the output that data is sorted based on keys.

Python3

import json
 
# Create a dictionary with unsorted keys
marks = {
    "Binod": 49,
    "Aparna": 71,
    "Jaya": 83,
    "Deepak": 89
}
 
# Convert the dictionary to a
# JSON string with sorted keys
json_string = json.dumps(marks,
                         sort_keys=True)
 
print(json_string)

                    

Output
{"Aparna": 71, "Binod": 49, "Deepak": 89, "Jaya": 83}

Difference Between Dictionary and JSON

S.No.

Dictionary

JSON

1.

JSON (JavaScript Object Notation) is a data interchange format used to store and exchange data between systems.

A dictionary in Python is a built-in data structure used to store a collection of key-value pairs.

2.

JSON keys must be strings and enclosed in double quotes.

Dictionary keys can be of various data types, including strings, numbers, and tuples (immutable types).

3.

JSON has a strict syntax with key-value pairs separated by colons (:), and pairs separated by commas (,). Curly braces {} enclose JSON objects.

Python dictionaries use curly braces {} to enclose key-value pairs, with colons : separating keys and values.

4.

JSON keys and string values must be enclosed in double quotes (e.g., “key”: “value”).

In Python dictionaries, keys can be specified without quotes (e.g., key: “value”), although quotes are also allowed.

5.

Eg. {“name”: “Ram”, “age”: 30}

Eg. {“name”: “Shyam”, “age”: 30}

6.

JSON values are accessed using keys as strings (e.g., data[“name”]).

Dictionary values are accessed using keys (e.g., data[“name”]) or using the get() method.

7.

JSON data can be saved to and loaded from files using functions like json.dump() and json.load().

Python dictionaries can also be serialized to files using various methods, but you need to handle the serialization/deserialization logic yourself.




Last Updated : 06 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads