Convert a Python dict to JSON
json.dumps() turns a dictionary you already have in Python into a JSON string. It also maps True, False, and None for you.
To convert a Python dict to JSON, call json.dumps(). It returns a string. Use it when the dictionary already exists in the process and you need JSON for an HTTP request, a cache, or a message. To write a file, use json.dump() instead of building the string yourself.
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. A list, or a list of dicts, uses the same function: Python list to JSON.
A copied dict is text, not a dict
json.dumps() does not parse a string such as {'name': 'Ada', 'active': True}. That text is Python syntax. Passing it to json.dumps() encodes it as one JSON string, quotes included. Passing it to json.loads() fails on the single quotes and on True.
When the dict is already an object, call json.dumps(). When you only have the copied text, parse the literal and then encode it:
import ast
import json
text = "{'name': 'Ada', 'active': True, 'score': None}"
print(json.dumps(ast.literal_eval(text)))
# {"name": "Ada", "active": true, "score": null}
ast.literal_eval() accepts literals only. Do not use eval() on a paste. Limits are in ast.literal_eval() vs eval(). For a one-off paste, the online dict to JSON converter does this in the browser and does not upload it.
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
| Option | Use |
|---|---|
indent=2 | Pretty-print nested JSON. |
sort_keys=True | Write object keys in a stable alphabetical order. |
ensure_ascii=False | Keep 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.