Sling Academy
Home/Python/Python: How to Create a JSON String from a Dictionary

Python: How to Create a JSON String from a Dictionary

Last updated: February 12, 2024

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.

Next Article: Python: Using variables as dictionary keys (basic and advanced examples)

Previous Article: Python: Checking if a value exists in a dictionary

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types