How to Convert a Python Dictionary to JSON String

In this tutorial, we will learn how to convert a Python dictionary to a JSON string using the built-in json module.

The process involves importing the json library, using json.dumps() to serialize the dictionary into a JSON-formatted string, and optionally formatting the output with indentation or sorting. This is essential for data exchange with APIs, configuration files, or storing structured data.

Steps:
1. Import the json module.
2. Create a Python dictionary.
3. Use json.dumps(dictionary) to convert it to a JSON string.
4. Customize output with indent or sort_keys parameters.

Code Example:

import json

# Create a Python dictionary
data = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}

# Convert dictionary to JSON string
json_str = json.dumps(data, indent=4, sort_keys=True)

# Print the JSON string
print(json_str)
Step-by-Step Explanation:
Step 1: Import the json Module:

The json module is part of Python’s standard library and provides functions to work with JSON data. Start by importing it:

import json
Step 2: Create a Python Dictionary:

A dictionary is a collection of key-value pairs. In this example, we create a dictionary with three keys: “name”, “age”, and “city”.

data = {
"name": "Alice",
"age": 30,
"city": "Paris"
}

-> “name”: A string value (“Alice”).
-> “age”: A numeric value (30).
-> “city”: Another string value (“Paris”).

Step 3: Convert the Dictionary to a JSON String:

Use the json.dumps() function to convert the dictionary into a JSON-formatted string. The dumps() function serializes the dictionary into a JSON string.

json_str = json.dumps(data, indent=4, sort_keys=True)

->data: The dictionary to be converted.
->indent=4: Adds 4 spaces of indentation to make the JSON string more readable.
->sort_keys=True: Sorts the keys in the dictionary alphabetically.

Step 4: Print the JSON String:

Finally, print the JSON string to see the result:

print(json_str)
Output:

The output will be a formatted JSON string:

{
"age": 30,
"city": "Paris",
"name": "Alice"
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top