pythonjsonformatter

Convert a Python dict to JSON with json.dumps()

Use Python's standard encoder to create valid JSON without brittle text replacements.

In Python, json.dumps() turns a Python value into a JSON string. It is the usual choice when you have a dictionary in memory and need JSON for an HTTP request, a file, a cache, or a message queue.

The smallest useful example

import json

payload = {"name": "Ada", "active": True, "score": None}
text = json.dumps(payload)
print(text)
# {"name": "Ada", "active": true, "score": null}

The Python values True and None become the JSON values true and null. You do not need to replace them yourself.

Make the output readable

pretty = json.dumps(payload, indent=2)
print(pretty)

indent=2 adds line breaks and two spaces for each nesting level. This makes a response or configuration file easier to inspect. For compact output, omit indent; this is often preferable when minimizing bytes matters.

Useful options

OptionUse
indent=2Pretty-print nested JSON.
sort_keys=TrueWrite object keys in a stable alphabetical order.
ensure_ascii=FalseKeep non-ASCII characters readable where your consumer supports UTF-8.
separators=(",", ":")Produce compact JSON without spaces.

Writing JSON to a file

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

json.dump() writes to an open file. json.dumps() returns a string. The extra s is a useful way to remember the distinction.

Values that need a decision

Standard JSON cannot directly represent a Python datetime, Decimal, set, bytes object, custom class, or function. Decide how your application should represent each one before serializing: a datetime may become an ISO-8601 string, a set may become a list, and a custom class may become a dictionary of selected fields.

By Python JSON Formatter ·