Contents
Convert Python Dictionary to JSON
To convert a Dict to JSON in Python, you can use json.dumps() function. json.dumps() function converts the Dictionary object into JSON string.
To use json.dumps() function, you need to import json package at the start of your Python program.
import json
The sample code snippet to use json.dumps() is
jsonStr = json.dumps(myDict)
where myDict is the dictionary that we would like to convert to JSON String.
Example 1: Convert Dictionary to JSON
In the following program, we will initialize a Python dictionary, and convert it into JSON string using dumps() function of json package.
Python Program
import json
myDict = {'a':'apple', 'b':'banana', 'c':'cherry'}
jsonStr = json.dumps(myDict)
print(jsonStr)
Run Output
{"a": "apple", "b": "banana", "c": "cherry"}
Example 2: Convert Dictionary with Different Types of Values to JSON
Dictionary is a collection of key:value pairs. In this example, we will take a dictionary with values of different datatypes and convert it into JSON string using json.dumps().
Python Program
import json
myDict = {'a':['apple', 'avacado'], 'b':['banana', 'berry'], 'vitamins':2.0142}
jsonStr = json.dumps(myDict)
print(jsonStr)
Run The first and second values are a list of strings. The third value is a floating point number.
Output
{"a": ["apple", "avacado"], "b": ["banana", "berry"], "vitamins": 2.0142}
Example 3: Empty Dictionary to JSON
In the following program, we will take an empty dictionary, and convert it into JSON string.
Python Program
import json
myDict = {}
jsonStr = json.dumps(myDict)
print(jsonStr)
Run Output
{}
Summary
In this tutorial of Python Examples, we learned how to convert Dictionary to JSON string in Python.