How to convert dictionary to JSON in Python

Published on Aug. 22, 2023, 12:16 p.m.

To convert a dictionary to JSON in Python, you can use the json.dumps() function from the built-in json module. This function takes a Python object (such as a dictionary) as input and returns a JSON-formatted string.

Here’s an example:

import json

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
my_json = json.dumps(my_dict)

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

In this example, we define a dictionary my_dict containing some key-value pairs. We use the json.dumps() function to convert the dictionary into a JSON-formatted string called my_json. The resulting string is equivalent to the original dictionary contents, but in JSON format.

Note that the json.dumps() function can also take additional parameters to customize the JSON output, such as specifying the indentation level or handling non-ASCII characters.

In general, converting a dictionary to JSON can be useful when you need to transfer or store the dictionary data in a standardized, text-based format.

Tags:

related content