Python dict to JSON: Serialize Text or a File

Python dictionary converted to JSON text and a JSON file

For a Python dict to JSON conversion, use json.dumps() when you need JSON text in memory. Use json.dump() when you need to write the dictionary directly to a file. Both functions serialize Python data, but they produce different outputs.

To convert a dict to JSON in Python, import the standard-library json module and pass your dictionary to the appropriate function. JSON uses double-quoted strings and standardized values, so str() or repr() is not a substitute for serialization.

Python dict to JSON with json.dumps(): Get JSON Text

json.dumps() returns a JSON-formatted Python string. It does not create a file or modify the original dictionary.

import json
data = {“name”: “Ada”, “active”: True, “roles”: [“admin”, “editor”]}
json_text = json.dumps(data)

The value of json_text is a string such as {“name”: “Ada”, “active”: true, “roles”: [“admin”, “editor”]}. Notice that Python’s True becomes JSON’s true. Use this approach when sending a payload through an API, storing serialized text in a database, or passing JSON to another component.

For readable output, add formatting options directly to the call:

json_text = json.dumps(data, indent=2)

The return type remains str, whether the output is compact or indented.

Write a dict to a JSON file with json.dump() using UTF-8 encoding

json.dump() writes JSON to an open, file-like object and returns None. Open the file with write mode and explicit UTF-8 encoding:

with open(“data.json”, “w”, encoding=”utf-8″) as file:
    json.dump(data, file, indent=2, ensure_ascii=False)

This creates or replaces data.json. The file contains JSON, while data remains a Python dictionary in memory. The with statement closes the file even if an error occurs. Unlike json.dumps(), json.dump() does not return the serialized document as a string.

Use encoding=”utf-8″ for predictable handling of names, labels, and other non-ASCII characters. The encoding controls how Python writes characters to the file; it is separate from JSON’s formatting options.

Format dict to JSON in Python with indent, Unicode, and sorted keys

  • indent=2 adds two spaces per nesting level. Use indent=4 for more spacing, or omit it for compact output.
  • ensure_ascii=False keeps characters such as é and 東京 readable. The default, True, escapes them with Unicode sequences such as \u00e9.
  • sort_keys=True writes object keys in alphabetical order. This makes generated files easier to compare and produces stable output for tests.

For a consistently formatted JSON string, combine the options: json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True). Key ordering affects presentation, not the meaning of a JSON object.

Convert a Python dict to JSON with supported types and a default handler

The built-in encoder supports dictionaries, lists, tuples, strings, integers, floating-point numbers, booleans, and None. These become JSON objects, arrays, strings, numbers, true, false, and null. JSON object keys should be strings; Python also accepts some simple non-string keys and converts them to strings.

Values such as sets, bytes, dates, decimals, and most custom objects are not serializable by default. The encoder raises TypeError when it encounters one. Supply a default function that converts a known type into a JSON-supported value:

from datetime import date, datetime
def encode_value(value):
    if isinstance(value, (date, datetime)):
        return value.isoformat()
    raise TypeError(f”Unsupported type: {type(value).__name__}”)

Then pass it to either serializer: json.dumps(data, default=encode_value) or json.dump(data, file, default=encode_value). This strategy stores dates as ISO 8601 strings and fails clearly for types you have not deliberately mapped.