Python Dictionary to JSON
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.
Examples
1. Convert a 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)
Output
{"a": "apple", "b": "banana", "c": "cherry"}
2. Convert dictionary with values of different types 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)
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}
3. Convert 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)
Output
{}
Summary
In this Python JSON Tutorial, we learned how to convert Dictionary to JSON string in Python.