Coding

Python json.load vs json.loads: Difference, Examples and Errors

json.load(f) reads and parses JSON from a file object, while json.loads(s) parses JSON that is already in a string, bytes or bytearray. The trailing "s" means string: use load with open(), and loads with text you already have in memory.

import json

# From a file: json.load takes the file object
with open("config.json", encoding="utf-8") as f:
    config = json.load(f)

# From a string: json.loads takes the text
config = json.loads('{"name": "alex", "port": 8080}')

Both return the same Python objects: JSON objects become dict, arrays become list, true/false become True/False, and null becomes None.

json.load vs json.loads at a glance

FunctionInputOutputTypical use
json.load(fp)File object with a .read() method (text or binary)Python objectReading a .json file
json.loads(s)str, bytes or bytearrayPython objectAPI responses, message queues, database columns, one line of a JSONL file
json.dump(obj, fp)Python object and a writable fileWrites to the fileSaving a .json file
json.dumps(obj)Python objectstrSending JSON over HTTP, logging, storing in a text column

The signatures in the Python docs are otherwise identical: both accept the same keyword arguments, such as object_hook, parse_float and object_pairs_hook.

json.load is just json.loads plus read()

You can see this in CPython's source. Run python -c "import json, inspect; print(inspect.getsource(json.load))" and the body of the function ends with:

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

Two practical consequences. First, json.load is not a streaming parser: it reads the whole file into memory before parsing, exactly like json.loads(f.read()). Second, there is no speed difference worth choosing between them. Pick the one that matches what you have.

The errors you get when you mix them up

These are the real messages from Python 3.12.

Passing a filename to json.load:

>>> json.load("config.json")
AttributeError: 'str' object has no attribute 'read'

json.load calls .read() on whatever you give it, and a string has no such method. Open the file first and pass the file object.

Passing a file object to json.loads:

>>> json.loads(open("config.json"))
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

Passing None, which usually means a function upstream returned nothing:

>>> json.loads(None)
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

JSONDecodeError messages and what they mean

json.JSONDecodeError is a subclass of ValueError, and its message always ends with the line, column and character position where parsing failed:

InputError messageCause
""Expecting value: line 1 column 1 (char 0)Empty string, often an empty HTTP body or empty file
{'a': 1}Expecting property name enclosed in double quotes: line 1 column 2 (char 1)Single quotes: a Python dict literal, not JSON
{"a": 1,}Expecting property name enclosed in double quotes: line 1 column 9 (char 8)Trailing comma, which JSON does not allow
{"a": 1Expecting ',' delimiter: line 1 column 8 (char 7)Truncated document
Two JSON objects on two linesExtra data: line 2 column 1 (char 22)A JSON Lines file parsed as one document
File starting with a UTF-8 BOMUnexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)Saved by an editor that adds a byte order mark

"Expecting value: line 1 column 1 (char 0)" is the most common one in practice. It almost never means your JSON is subtly wrong; it means there was no JSON at all. Print repr() of the input before parsing: an empty string, an HTML error page or a None turned into a string is the usual culprit.

The exception carries the position as attributes, so you can report it precisely:

try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    print(f"Bad JSON at line {e.lineno}, column {e.colno}: {e.msg}")

Reading a JSON Lines (.jsonl) file

A JSON Lines file has one complete JSON document per line. json.load fails on it with Extra data, because after the first document it finds more text. Read it line by line and use json.loads on each line:

with open("events.jsonl", encoding="utf-8") as f:
    events = [json.loads(line) for line in f if line.strip()]

Result for a two-line file:

[{'id': 1, 'ok': True}, {'id': 2, 'ok': False}]

The if line.strip() skips blank lines, including a trailing empty line at the end of the file. More patterns for this loop are in how to read a file line by line in Python.

Encoding: open JSON files as UTF-8

RFC 8259 requires JSON exchanged between systems to be encoded in UTF-8, and the Python tutorial says the same for JSON files. Always pass encoding="utf-8" to open(). On Windows, Python versions before 3.15 otherwise use the locale encoding, which breaks on non-ASCII characters.

If the file came from an editor that adds a byte order mark, open it with encoding="utf-8-sig", which strips the BOM. The error message in the table above tells you exactly that.

json.loads also accepts bytes directly and detects UTF-8, UTF-16 or UTF-32, so json.loads(b'{"a": 1}') works without decoding first.

The same rule for writing: dump vs dumps

settings = {"name": "alex", "tags": ["dev", "ops"]}

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

text = json.dumps(settings)   # '{"name": "alex", "tags": ["dev", "ops"]}'

ensure_ascii=False writes characters such as é as themselves instead of é escapes. Don't call json.dump twice on the same file to append records: the docs warn that JSON is not a framed protocol, so the result is an invalid file. Write a list in one call, or write JSON Lines with one json.dumps(record) plus "\n" per line.

Surprises worth knowing

  • Duplicate keys don't raise. json.loads('{"x": 1, "x": 2}') returns {'x': 2}: the last value wins. Use object_pairs_hook if you need to reject duplicates.
  • NaN and Infinity are accepted. Python reads and writes NaN and Infinity by default even though the JSON standard doesn't allow them. Pass allow_nan=False to dumps if another system will parse your output.
  • Validate from the command line. python -m json.tool config.json pretty-prints a valid file and prints the error position for an invalid one. Python 3.14 and later also accept python -m json.

If you are deciding which format to use for a config file in the first place, JSON vs YAML vs TOML compares the same config in all three.

Frequently asked questions

What does the s in json.loads stand for?
String. json.loads parses a JSON document held in a str (or bytes or bytearray), and json.dumps returns a str. The functions without the s, json.load and json.dump, work with file objects instead.
Is json.load faster than json.loads?
Not meaningfully. In CPython, json.load is a thin wrapper that calls fp.read() and passes the result to json.loads, so both read the entire document into memory and parse it with the same decoder.
Which one do I use for an HTTP response body?
json.loads. An HTTP library hands you the body as a str or bytes, not as an open file, so pass that text to json.loads. If the body is empty or an HTML error page, you get JSONDecodeError: Expecting value: line 1 column 1 (char 0), so check the status code first.
Why does json.loads fail on single quotes?
JSON requires strings and object keys in double quotes. A string like {'a': 1} is a Python dict literal, not JSON, so json.loads raises JSONDecodeError: Expecting property name enclosed in double quotes. Fix the producer to emit real JSON, for example with json.dumps.

Sources