Python: How to Create a JSON String from a Dictionary

Updated: February 20, 2023 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.


import json

my_dict = {
  "website": "Sling Academy",
  "site_url": "",
  "age": 10

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

print(type (json_data))


<class 'str'>
    "website": "Sling Academy",
    "site_url": "",
    "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.

Notify of
Inline Feedbacks
View all comments