How to print Python dictionary into JSON format?

In Python, dictionaries are used to store structured data in key-value pairs. When we need to display this data in a readable format or send it over the internet (such as to an API), we convert the dictionary to JSON (JavaScript Object Notation) format.

Python provides a built-in json module to handle dictionary-to-JSON conversions seamlessly.

JSON is a lightweight, text-based data interchange format that's easy for humans to read and write. Originally derived from JavaScript, it's now language-independent and widely used for data exchange.

Creating a Sample Dictionary

Let's start by creating a dictionary with product information −

# Creating a dictionary with product details
product = {
    "Product": "Mobile",
    "Model": "XUT",
    "Units": 120,
    "Available": "Yes"
}

# Display the dictionary
print("Original dictionary:", product)
print("Product:", product["Product"])
print("Units:", product["Units"])
Original dictionary: {'Product': 'Mobile', 'Model': 'XUT', 'Units': 120, 'Available': 'Yes'}
Product: Mobile
Units: 120

Using json.dumps() Method

The json.dumps() function converts a Python dictionary to a JSON-formatted string −

import json

# Creating a dictionary
product = {
    "Product": "Mobile",
    "Model": "XUT", 
    "Units": 120,
    "Available": "Yes"
}

# Convert dictionary to JSON string
json_string = json.dumps(product)
print("JSON format:", json_string)

# Pretty print with indentation
json_pretty = json.dumps(product, indent=4)
print("\nPretty JSON format:")
print(json_pretty)
JSON format: {"Product": "Mobile", "Model": "XUT", "Units": 120, "Available": "Yes"}

Pretty JSON format:
{
    "Product": "Mobile",
    "Model": "XUT",
    "Units": 120,
    "Available": "Yes"
}

Using Custom __str__ Method

You can create a custom class that inherits from dict and overrides the __str__ method to return JSON format −

import json

# Custom dictionary class with JSON string representation
class JSONDict(dict):
    def __str__(self):
        return json.dumps(self, indent=2)

# Create instance with product data
product = JSONDict({
    "Product": "Mobile",
    "Model": "XUT",
    "Units": 120,
    "Available": "Yes"
})

print("JSON format using custom class:")
print(product)
JSON format using custom class:
{
  "Product": "Mobile",
  "Model": "XUT",
  "Units": 120,
  "Available": "Yes"
}

JSON Formatting Options

The json.dumps() method provides several parameters for formatting −

import json

data = {"name": "John", "age": 30, "city": "New York"}

# Different formatting options
print("Compact:", json.dumps(data))
print("Indented:", json.dumps(data, indent=4))
print("Sorted keys:", json.dumps(data, sort_keys=True))
print("No spaces:", json.dumps(data, separators=(',', ':')))
Compact: {"name": "John", "age": 30, "city": "New York"}
Indented: {
    "name": "John",
    "age": 30,
    "city": "New York"
}
Sorted keys: {"age": 30, "city": "New York", "name": "John"}
No spaces: {"name":"John","age":30,"city":"New York"}

Comparison

Method Use Case Advantages
json.dumps() General JSON conversion Simple, flexible formatting options
Custom __str__ Reusable JSON objects Automatic JSON output when printing

Conclusion

Use json.dumps() for straightforward dictionary-to-JSON conversion. For pretty formatting, add indent=4 parameter. Custom __str__ methods are useful when you need automatic JSON representation for custom classes.

Updated on: 2026-03-24T18:50:04+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements