Convert Python dict output to JSON
You copied a dict out of a log, a notebook cell or a print() call, and now a JSON parser rejects it. Paste it above and click Convert to JSON. The converter reads the text as Python, not with search and replace, so an apostrophe inside "It's complicated" or a double quote inside 'She said "hi"' comes out correctly escaped. Use Find the error to see exactly where a strict JSON parser stops, with the line, column and a caret under the character.
Before:
{'id': 1042, 'active': True, 'manager': None, 'title': "It's complicated",
'location': (51.5072, -0.1276), 'balance': Decimal('1999.90'),
'created': datetime.datetime(2024, 5, 1, 9, 30, tzinfo=datetime.timezone.utc)}
After:
{
"id": 1042,
"active": true,
"manager": null,
"title": "It's complicated",
"location": [51.5072, -0.1276],
"balance": 1999.90,
"created": "2024-05-01T09:30:00+00:00"
}
Why a printed Python dict is not JSON
print(d) and str(d) show the dict's repr: Python source syntax. It looks like JSON, but almost every value type is spelled differently.
| Python repr | Valid JSON | What the converter does |
|---|---|---|
'text' | "text" | Reads the string and writes it with double quotes, escaping any " inside |
True / False / None | true / false / null | Converted (only outside strings, so 'None of these' stays text) |
(1, 2), (1,), () | [1, 2], [1], [] | Tuples become arrays, as json.dumps does |
{'a', 'b'}, set() | ["a", "b"], [] | Sets become arrays (json.dumps raises TypeError instead) |
Decimal('19.90') | 19.90 | Written as an exact number, trailing zero kept |
datetime.datetime(2024, 5, 1, 9, 30) | "2024-05-01T09:30:00" | ISO 8601 string; tzinfo=datetime.timezone.utc adds +00:00, a timedelta offset adds e.g. +05:30 |
datetime.date(2024, 5, 1) | "2024-05-01" | ISO date string |
UUID('...') | "..." | The UUID text as a string |
b'raw', u'text' | "raw", "text" | Prefix removed, \x.. escapes decoded |
10L (Python 2) | 10 | Suffix removed |
nan, inf | no equivalent | Replaced with null |
{1: 'a'} | {"1": "a"} | Non-string keys become strings, like json.dumps |
Anything else that looks like a constructor call, such as MyClass(x=1), is kept as a string so no data disappears silently, and the change list tells you which ones.
Convert a dict to a JSON string in Python: json.dumps
If you control the code, never print the dict and convert the text. Serialise it directly. json.dumps returns a str containing JSON:
import json
user = {"id": 1042, "active": True, "manager": None, "location": (51.5, -0.12)}
text = json.dumps(user)
# '{"id": 1042, "active": true, "manager": null, "location": [51.5, -0.12]}'
print(json.dumps(user, indent=2, sort_keys=True)) # pretty-printed
People often ask for a "JSON object" from a dict. In Python, the dict already is the object. JSON is the text form you send or save, and json.loads(text) turns that text back into a dict.
Write a Python dict to a JSON file: json.dump
json.dump (no s) writes straight to a file object:
import json
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
with open("data.json", encoding="utf-8") as f:
data = json.load(f)
Pass encoding="utf-8" explicitly. Without it, Python uses the platform's default encoding, which on Windows has traditionally not been UTF-8. That matters once ensure_ascii=False lets characters like é through unescaped.
json.dumps options you will actually use
| Argument | Effect |
|---|---|
indent=2 | Pretty-print with 2-space indentation. The default (None) writes everything on one line. |
sort_keys=True | Sort object keys alphabetically. Useful for stable diffs and caching. |
ensure_ascii=False | Keep non-ASCII characters as they are. The default True writes "café" as "café". |
separators=(",", ":") | Most compact output, with no spaces after commas and colons. |
default=str | Called for objects json cannot serialise (datetime, Decimal, UUID). Here it turns them into strings. |
allow_nan=False | Raise ValueError instead of writing NaN or Infinity. Those tokens are not valid JSON, but json.dumps writes them by default. |
"Object of type datetime is not JSON serializable"
The json module only knows dict, list, tuple, str, int, float, bool and None. Everything else raises TypeError. The quick fix is default=str. Note that it gives "2024-05-01 09:30:00+00:00" with a space, not the T of ISO 8601. For cleaner output, write a small default function:
import json, datetime, decimal, uuid
def to_json(obj):
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
return obj.isoformat()
if isinstance(obj, decimal.Decimal):
return str(obj) # keep exact; use float(obj) if you prefer a number
if isinstance(obj, (set, frozenset)):
return sorted(obj)
if isinstance(obj, uuid.UUID):
return str(obj)
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")
json.dumps(data, default=to_json)
Raising for anything unexpected matters. A catch-all str() will happily serialise an object you never meant to send.
Already have the printed text? Use ast.literal_eval, not eval
If the repr text is all you have, for example from a log file, Python can read it back safely:
import ast, json
text = "{'id': 7, 'tags': ('a', 'b'), 'ok': True, 'note': None}"
data = ast.literal_eval(text) # only literals: no function calls, no code execution
print(json.dumps(data))
# {"id": 7, "tags": ["a", "b"], "ok": true, "note": null}
ast.literal_eval accepts strings, numbers, tuples, lists, dicts, sets, booleans and None. It refuses datetime.datetime(...) or Decimal(...) with ValueError: malformed node or string, because those are function calls. The converter on this page handles those common reprs too. Never use plain eval() on text you did not write, since it runs arbitrary code.
Errors you get when you feed a Python dict to a JSON parser
| Parser | Input | Error message |
|---|---|---|
Python json.loads | {'a': 1} | JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) |
Python json.loads | {"a": True} | JSONDecodeError: Expecting value: line 1 column 7 (char 6) |
JavaScript JSON.parse (Chrome, Node.js) | {'a': 1} | SyntaxError: Expected property name or '}' in JSON at position 1 (older versions: Unexpected token ' in JSON at position 1) |
Python json.dumps | a datetime value | TypeError: Object of type datetime is not JSON serializable |
Python json.dumps | a tuple used as a key | TypeError: keys must be str, int, float, bool or None, not tuple |
Big integers survive
Python integers have no size limit, so a dict can hold 12345678901234567890 without trouble. Many JSON tools in the browser run the result through JavaScript's JSON.parse, which rounds anything above 9007199254740991. This converter keeps the digits exactly as written and warns you when a number would be rounded by JavaScript. See JSON big integer precision loss for the details and fixes.
FAQ
How do I convert a Python dict to JSON?
In code, use json.dumps(my_dict) to get a JSON string, or json.dump(my_dict, f) to write it to a file. If you only have the printed dict (text with single quotes, True and None), paste it into the converter above and click Convert to JSON.
Why is str(dict) or print(dict) not valid JSON?
Because it is Python syntax, not JSON. Python prints strings with single quotes, writes True, False and None, shows tuples in parentheses, and prints objects such as Decimal('1.5') and datetime.datetime(...). JSON requires double quotes, lowercase true, false and null, and only objects, arrays, strings, numbers, booleans and null.
Can I just replace single quotes with double quotes?
No. A dict like {'title': "It's here"} becomes {"title": "It"s here"}, which is broken, and a string containing double quotes breaks the same way. Parse the text instead: ast.literal_eval in Python, or the converter on this page, which reads each string properly.
How do I fix "Object of type datetime is not JSON serializable"?
Pass a default function: json.dumps(data, default=str) turns datetime, Decimal and other unknown objects into strings. For ISO 8601 output, use a function that returns obj.isoformat() for dates and raises TypeError for anything you did not expect.
How do I write a Python dict to a JSON file?
Open the file in text mode with UTF-8 and call json.dump: with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False). Use json.load to read it back.
What is the difference between json.dumps and json.dump?
json.dumps returns the JSON as a string. json.dump writes it to an open file object. Both take the same options, such as indent, sort_keys, ensure_ascii and default.
Is my data uploaded anywhere?
No. The converter runs in JavaScript in your browser. Nothing you paste is sent to a server.