Python JSON: dumps, loads, Type Changes, and Common Errors
json.dumps(obj) returns a JSON string, and json.loads(text) turns a JSON string back into Python objects. json.dump(obj, f) and json.load(f) do the same with an open file instead of a string. A round trip does not always return what you started with: tuples come back as lists, and number keys come back as strings.
On this page▾
- How does json.dumps work in Python?
- Making it readable
- What changes on the round trip
- Non-English text
- Reading the errors
- What is the difference between json.dump and json.dumps?
- Frequently asked questions
- What does json.dumps do in Python?
- What is the difference between json.dump and json.dumps?
- What does json.loads do in Python?
- Before saving or accepting JSON
- Why does Python write NaN even though another app rejects it?
- What happens if an object repeats a key?
How does json.dumps work in Python?
| Function | Input | Result |
|---|---|---|
json.dumps(obj) |
Python value | JSON str |
json.dump(obj, f) |
Python value and writable file | Writes JSON text to the file |
json.loads(text) |
JSON text | Python value |
json.load(f) |
Readable file containing JSON | Python value |
The "s" in dumps and loads stands for string. dumps returns a string, and loads takes one.
import json
order = {"id": 7, "items": ["tea", "cake"], "paid": True, "note": None, "total": 12.5}
text = json.dumps(order)
print(text)
print(type(text))
{"id": 7, "items": ["tea", "cake"], "paid": true, "note": null, "total": 12.5}
<class 'str'>
True became true and None became null. The reference gives the full conversion table:
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True / False | true / false |
| None | null |
Going the other way:
back = json.loads(text)
print(back)
print(back == order)
print(back["items"][1])
{'id': 7, 'items': ['tea', 'cake'], 'paid': True, 'note': None, 'total': 12.5}
True
cake
This particular round trip returns an equal dictionary. That does not mean every Python value or every consumer of JSON preserves the same types and numeric precision.
Making it readable
indent adds line breaks and spacing, and sort_keys=True orders the keys. Both are options the reference lists for pretty printing.
print(json.dumps(order, indent=2, sort_keys=True))
{
"id": 7,
"items": [
"tea",
"cake"
],
"note": null,
"paid": true,
"total": 12.5
}
Without indent, everything is on one line. The reference also shows separators=(',', ':') for the most compact output.
What changes on the round trip
JSON has arrays but no tuples, so a tuple is written as an array and comes back as a list:
data = {"point": (3, 4), "ok": True, "none": None}
print(json.dumps(data))
print(json.loads(json.dumps(data)))
{"point": [3, 4], "ok": true, "none": null}
{'point': [3, 4], 'ok': True, 'none': None}
Keys have a similar rule. The reference states that keys in JSON are always strings, so converting a dictionary with non-string keys and back can produce a dictionary that is not equal to the original:
keys = {1: "one", 2: "two"}
print(json.dumps(keys))
print(json.loads(json.dumps(keys)))
print(json.loads(json.dumps(keys)) == keys)
{"1": "one", "2": "two"}
{'1': 'one', '2': 'two'}
False
If you use IDs as dictionary keys and save them to JSON, convert them back with int() after loading.
Non-English text
By default ensure_ascii is true, and the reference says the output then escapes all non-ASCII characters. The text is still valid and loads back correctly, but it is hard to read. Set it to false to keep the characters:
print(json.dumps({"city": "Zürich"}))
print(json.dumps({"city": "Zürich"}, ensure_ascii=False))
{"city": "Z\u00fcrich"}
{"city": "Zürich"}
Reading the errors
Invalid JSON raises json.JSONDecodeError. These three strings are common mistakes when writing JSON by hand:
for bad in ["{'a': 1}", '{"a": 1,}', '{"a": True}']:
try:
json.loads(bad)
except json.JSONDecodeError as e:
print(bad, "->", e)
{'a': 1} -> Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
{"a": 1,} -> Illegal trailing comma before end of object: line 1 column 8 (char 7)
{"a": True} -> Expecting value: line 1 column 7 (char 6)
JSON requires double quotes, does not allow a trailing comma, and spells booleans in lowercase. The error message gives the line and column where parsing stopped, which is where to look first. The exact wording of these messages can differ between Python versions.
Values JSON has no type for raise a TypeError when you write them:
json.dumps({"when": {1, 2}})
TypeError: Object of type set is not JSON serializable
Convert a set with sorted() or list() before dumping it. The reference also describes a default= function for teaching dumps how to handle your own types.
What is the difference between json.dump and json.dumps?
Without the "s", json.dump(obj, file) writes to an open file and json.load(file) reads from one:
with open("order.json", "w", encoding="utf-8") as f:
json.dump(order, f, indent=2)
with open("order.json", encoding="utf-8") as f:
print(json.load(f) == order)
True
The tutorial notes that JSON files must be encoded in UTF-8, which is why the example passes encoding="utf-8" explicitly.
Opening files for reading and writing is covered in How to Read and Write Text Files in Python.
Frequently asked questions
What does json.dumps do in Python?
It serializes a Python value to a JSON-formatted string. For example, Python True becomes JSON true, and None becomes null.
What is the difference between json.dump and json.dumps?
json.dumps(obj) returns a string. json.dump(obj, f) writes JSON text to a file-like object whose write() method accepts strings.
What does json.loads do in Python?
It parses a JSON document into Python values. By default, arrays become lists, objects become dictionaries and invalid JSON raises json.JSONDecodeError.
Before saving or accepting JSON
Repeated calls to json.dump() do not create a valid multi-record JSON file. JSON does not frame separate objects automatically. Put the records in one list and serialize that list once if the file is meant to contain a single JSON document.
records = [{"id": 1}, {"id": 2}]
text = json.dumps(records)
print(json.loads(text))
[{'id': 1}, {'id': 2}]
For untrusted input, limit how much data you accept before parsing: a malicious JSON string can consume substantial CPU and memory.
Why does Python write NaN even though another app rejects it?
The default encoder permits NaN, Infinity and -Infinity, which are outside the JSON specification. Use json.dumps(data, allow_nan=False) to raise ValueError instead of writing those nonstandard values. This option controls encoding, not the separate decoder settings.
What happens if an object repeats a key?
The default decoder retains the last value. For example, json.loads('{"id": 1, "id": 2}') produces {'id': 2} rather than an error. Do not assume that a successful load has detected duplicate names.
Sources
About this guide
Howlane operator · Checked against the official sources listed above. It is general information, not professional advice.
AboutEditorial standardsCorrectionsReport an error
Edit history
- Updated
- Updated
- Updated
- Updated
- Published