Python Dict to JSON - Convert Dictionary to JSON

Quick guide to converting Python dictionaries to JSON strings and files

Published: January 2025 • 7 min read

Converting Python dictionaries to JSON is essential when building APIs, saving configuration files, or sending data over networks. Python's built- in json module makes this conversion straightforward with two main functions.

This guide shows you exactly how to convert Python dictionaries to JSON, with practical examples for JSON strings, files, formatting, and error handling. You can also use our JSON to Python converter for the reverse operation.

Quick Answer: Use json.dumps(dict) to convert dict to JSON string, or json.dump(dict, file) to save to a file.

Basic: Dict to JSON String

The json.dumps() function converts a Python dictionary to a JSON string. The 's' stands for "string". Read more in the official Python documentation.

Simple Example

import json

# Python dictionary
user = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "is_active": True
}

# Convert dict to JSON string
json_string = json.dumps(user)

print(type(json_string))  # Output: <class 'str'>
print(json_string)
# Output: {"name": "Alice", "age": 30, "city": "New York", "is_active": true}

The dictionary is converted to a compact JSON string. Note: Python's True becomes JSON's true.

Pretty Print JSON with Indentation

Use the indent parameter to create human-readable JSON. Perfect for debugging and configuration files. Learn more about JSON formatting in Python.

Without Indentation (Compact)

import json

data = {"name": "Bob", "age": 25, "skills": ["Python", "JavaScript"]}

json_string = json.dumps(data)
print(json_string)

# Output: {"name": "Bob", "age": 25, "skills": ["Python", "JavaScript"]}

With Indentation (Readable)

import json

data = {"name": "Bob", "age": 25, "skills": ["Python", "JavaScript"]}

json_string = json.dumps(data, indent=2)
print(json_string)

# Output:
# {
#   "name": "Bob",
#   "age": 25,
#   "skills": [
#     "Python",
#     "JavaScript"
#   ]
# }

The indent=2 parameter adds 2-space indentation for readability.

Save Dict to JSON File

Use json.dump() (without the 's') to write a dictionary directly to a file. For a complete guide, see our Python Write JSON to File tutorial.

Writing to File

import json

# Python dictionary
config = {
    "database": "postgresql",
    "host": "localhost",
    "port": 5432,
    "debug": True
}

# Write dict to JSON file
with open('config.json', 'w') as file:
    json.dump(config, file, indent=2)

print("Dictionary saved to config.json")

# config.json content:
# {
#   "database": "postgresql",
#   "host": "localhost",
#   "port": 5432,
#   "debug": true
# }

The with statement automatically closes the file after writing.

Converting Nested Dictionaries

Python dictionaries with nested structures convert to nested JSON objects seamlessly.

Nested Dictionary Example

import json

# Nested dictionary
user_data = {
    "user": {
        "id": 1,
        "name": "Alice",
        "profile": {
            "email": "[email protected]",
            "preferences": {
                "theme": "dark",
                "notifications": True
            }
        }
    }
}

# Convert to JSON
json_string = json.dumps(user_data, indent=2)
print(json_string)

# Output:
# {
#   "user": {
#     "id": 1,
#     "name": "Alice",
#     "profile": {
#       "email": "[email protected]",
#       "preferences": {
#         "theme": "dark",
#         "notifications": true
#       }
#     }
#   }
# }

All nested dictionaries are converted to nested JSON objects automatically.

Handling Lists and Complex Types

Python lists become JSON arrays. Here's how different Python types convert to JSON:

Python TypeJSON TypeExample
dictobject{"key": "value"}
list, tuplearray[1, 2, 3]
strstring"hello"
int, floatnumber42, 3.14
TruetrueBoolean
FalsefalseBoolean
NonenullNull value

Example with Multiple Types

import json

data = {
    "name": "Product",
    "price": 29.99,
    "quantity": 100,
    "in_stock": True,
    "discount": None,
    "tags": ["electronics", "gadgets"],
    "specs": {"weight": "500g", "color": "black"}
}

json_string = json.dumps(data, indent=2)
print(json_string)

# Output:
# {
#   "name": "Product",
#   "price": 29.99,
#   "quantity": 100,
#   "in_stock": true,
#   "discount": null,
#   "tags": [
#     "electronics",
#     "gadgets"
#   ],
#   "specs": {
#     "weight": "500g",
#     "color": "black"
#   }
# }

Sorting Dictionary Keys

Use sort_keys=True to alphabetically sort keys in the JSON output. Useful for consistent output and version control. Learn more from GeeksforGeeks.

Sorted Keys Example

import json

data = {
    "zebra": 1,
    "apple": 2,
    "mango": 3,
    "banana": 4
}

# Without sorting
json_unsorted = json.dumps(data, indent=2)
print(json_unsorted)
# Output: {"zebra": 1, "apple": 2, "mango": 3, "banana": 4}

# With sorting
json_sorted = json.dumps(data, indent=2, sort_keys=True)
print(json_sorted)

# Output:
# {
#   "apple": 2,
#   "banana": 4,
#   "mango": 3,
#   "zebra": 1
# }

Sorted keys make JSON output consistent across runs, perfect for Git diffs.

Real-World Examples

Example 1: Sending Dict to API

import json
import requests

# Python dictionary
user_data = {
    "username": "alice",
    "email": "[email protected]",
    "age": 30
}

# Convert dict to JSON string for API
json_payload = json.dumps(user_data)

# Send to API
response = requests.post(
    'https://api.example.com/users',
    data=json_payload,
    headers={'Content-Type': 'application/json'}
)

print(response.status_code)

Common pattern for sending Python data to REST APIs.

Example 2: Creating Config File

import json

# Application settings dictionary
settings = {
    "app_name": "MyApp",
    "version": "1.0.0",
    "database": {
        "host": "localhost",
        "port": 5432,
        "name": "myapp_db"
    },
    "features": {
        "enable_cache": True,
        "max_retries": 3
    }
}

# Save to config file
with open('settings.json', 'w') as file:
    json.dump(settings, file, indent=2, sort_keys=True)

print("Configuration saved to settings.json")

Example 3: Export Data from Objects

import json

# List of dictionaries
users = [
    {"id": 1, "name": "Alice", "role": "admin"},
    {"id": 2, "name": "Bob", "role": "user"},
    {"id": 3, "name": "Charlie", "role": "user"}
]

# Convert to JSON and save
with open('users.json', 'w') as file:
    json.dump(users, file, indent=2)

print(f"Exported {len(users)} users to users.json")

# users.json content:
# [
#   {
#     "id": 1,
#     "name": "Alice",
#     "role": "admin"
#   },
#   ...
# ]

Error Handling

Some Python objects can't be converted to JSON. Always handle TypeError exceptions. Learn more from Python docs.

Non-Serializable Objects

import json
from datetime import datetime

# Dictionary with datetime (not JSON serializable)
data = {
    "event": "Meeting",
    "timestamp": datetime.now()  # This will cause an error!
}

try:
    json_string = json.dumps(data)
except TypeError as e:
    print(f"Error: {e}")
    # Output: Object of type datetime is not JSON serializable

# Solution: Convert datetime to string
data["timestamp"] = datetime.now().isoformat()
json_string = json.dumps(data, indent=2)
print(json_string)

# Output:
# {
#   "event": "Meeting",
#   "timestamp": "2025-01-16T14:30:00.123456"
# }

Always convert datetime, sets, and custom objects to JSON-compatible types first.

Safe Conversion Function

import json

def dict_to_json(data, filepath=None):
    """
    Safely convert dict to JSON with error handling
    """
    try:
        json_string = json.dumps(data, indent=2, sort_keys=True)
        
        if filepath:
            with open(filepath, 'w') as file:
                file.write(json_string)
            print(f"JSON saved to {filepath}")
        
        return json_string
        
    except TypeError as e:
        print(f"Error: Cannot serialize data - {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

# Usage
user = {"name": "Alice", "age": 30}
json_output = dict_to_json(user, "user.json")

Common Issues & Solutions

1. DateTime Objects

Problem: datetime objects aren't JSON serializable.

Solution: Use .isoformat() or .strftime() to convert to string

2. Sets

Problem: Python sets can't be serialized to JSON.

Solution: Convert to list first: list(my_set)

3. Circular References

Problem: Dictionaries that reference themselves cause infinite loops.

Solution: Restructure data to remove circular references before conversion

4. Custom Objects

Problem: Custom class instances aren't serializable by default.

Solution: Convert to dict using __dict__ or vars()

Best Practices

1.
Use indent for readable files: Add indent=2 for config files and debugging
2.
Sort keys for consistency: Use sort_keys=True for version control and diffs
3.
Handle exceptions: Wrap json.dumps() in try-except for TypeError
4.
Convert non-serializable types: Convert datetime, sets, and custom objects before serialization
5.
Use context managers for files: Always use with open() to ensure files are properly closed
6.
Validate output: Use our JSON Validator to check the output

Quick Reference Cheat Sheet

Dict → JSON String

json_string = json.dumps(dict)

Dict → JSON File

json.dump(dict, open('file.json', 'w'))

Pretty Print

json.dumps(dict, indent=2)

Sort Keys

json.dumps(dict, sort_keys=True)

Combined Options

json.dumps(dict, indent=2, sort_keys=True)

External Resources

Summary

Converting Python dictionaries to JSON is straightforward with the json module:

  • Use json.dumps() to convert dict to JSON string
  • Use json.dump() to save dict to JSON file
  • Add indent parameter for readable output
  • Use sort_keys=True for consistent ordering
  • Convert datetime and custom objects to JSON-compatible types first