How to convert Python dictionary to JSON?

In this tutorial we will show to you create dictionary object and then convert the Python dictionary object to JSON.

How to convert Python dictionary to JSON?

How to convert Python dictionary to JSON? Python example to create dictionary and convert to JSON pretty print format

These days JSON is very popular in programming world and it is used for storing data for the program. The JSON stands for JavaScript Object Notation and is most favored format of data exchange between the applications. JSON is used to store and transfer of data between programs. It an easily be transferred over Internet using HTTP, HTTPS or any other protocol. In modern programming JSON is very frequently used for storing data, which can be transferred between the applications very easily.

If you are Python programmer you may have to work with the data in the JSON format. Python comes with the json module which can be use for parsing and working with the JSON data format. In this example I will show you how to instantiate Python dictionary and then convert the dictionary data into JSON format.

The json library of Python provides the following functions which we can use to convert dictionary object into JSON string:

  • json.dumps()
  • json.dump()

We will use json.dumps() function which converts any Python object such dictionary to JSON string. We will pass dictionary object to this function and function will return the JSON string representation of the object.

Here is the program to convert dictionary to JSON in Python:

Dictionary to JSON conversion in Python

Here is complete example of converting the Python dictionary to JSON:


import json

week ={
	"1":"Sunday",
	"2":"Monday",
	"3":"Tuesday",
	"4":"Wednesday",
	"5":"Thursday",
	"6":"Friday",
	"7":"Saturday"
}


# Serializing json   
json_object = json.dumps(week)  
print(json_object) 

#Get pretty format
json_object = json.dumps(week, indent=4)  
print(json_object) 

Here is the output of the program:

roseindia@roseindia-VirtualBox:~$ python3 1.py
{"1": "Sunday", "2": "Monday", "3": "Tuesday", "4": "Wednesday", "5": "Thursday", "6": "Friday", "7": "Saturday"}
{
    "1": "Sunday",
    "2": "Monday",
    "3": "Tuesday",
    "4": "Wednesday",
    "5": "Thursday",
    "6": "Friday",
    "7": "Saturday"
}
roseindia@roseindia-VirtualBox:~$ 

Here is the screenshot of program execution:

Dictionary to JSON conversion example in Python

In Python json library is used to work with the JSON data formats. You can use this library in many ways and in this tutorial we have learned to use this library to convert dictionary into JSON format. You can also use this library to read JSON file and parse the JSON data.

Here more examples of Python: