Python: How to Create a JSON String from a Dictionary

Updated: February 12, 2024 By: Goodman Post a comment

Creating JSON data from a Python dictionary isn’t a hard task. The programming language provides a built-in method named dumps() from the json module that can help us convert Python objects into JSON data with a single line of code.

Example:

import json

my_dict = {
  "website": "Sling Academy",
  "site_url": "https://www.slingacademy.com",
  "age": 10
}

json_data = json.dumps(my_dict, indent=4)

print(type (json_data))
print(json_data)

Output:

<class 'str'>
{
    "website": "Sling Academy",
    "site_url": "https://www.slingacademy.com",
    "age": 10
}

The my_dict dictionary is turned into a JSON string by using the json.dumps() method, which serializes a Python object to a JSON formatted string. The second argument indent specifies the number of spaces to use for indentation in the resulting JSON string (to improve readability). In this case, indent=4 adds 4 spaces for each level of indentation.