How json.loads and json.load handle bytes and bytearray in Python: encoding auto-detection and the strict parameter
The json.loads and json.load functions in Python accept bytes and bytearray inputs since version 3.6, automatically detecting UTF-8, UTF-16, or UTF-32 encoding. If the encoding is incorrect, UnicodeDecodeError is raised. The strict parameter controls handling of control characters in JSON strings. Practical scenarios and limitations are discussed.
On this page
The short answer
The json.loads and json.load functions in Python support bytes and bytearray inputs since version 3.6, automatically detecting the encoding as UTF-8, UTF-16, or UTF-32 without needing an explicit encoding parameter (which was removed in version 3.9). If the data is encoded in another encoding (e.g., cp1251 or latin-1), a UnicodeDecodeError is raised. The strict parameter (default True) forbids control characters inside JSON strings, while strict=False allows them. To read bytes from files, you can use Path.read_bytes() with json.loads or pass a binary file object directly to json.load. Note that auto-detection works only for UTF-8, UTF-16, and UTF-32, and a BOM at the start of the file causes a ValueError.
Input data: bytes and bytearray as input to json.loads
The json.loads function in Python accepts not only strings (str) but also byte objects (bytes and bytearray) since version 3.6. This allows processing JSON data directly from network streams, files, or other binary sources without prior decoding to a string. For example, if data comes from an HTTP response as bytes, it can be passed directly to json.loads without additional conversions.
This approach is convenient in scenarios where data is originally in binary form, such as reading files in binary mode or handling network protocols that return raw bytes. However, it is important to remember that json.loads automatically detects the encoding only for UTF-8, UTF-16, and UTF-32. If the data is encoded in another encoding (e.g., cp1251 or latin-1), a UnicodeDecodeError will be raised.
import json
# Пример: байтовый вход в UTF-8
payload = b'{"name": "caf\\u00e9", "data": [1, 2, 3]}'
decoded = json.loads(payload)
print(decoded) # {'name': 'café', 'data': [1, 2, 3]}Practical tip
For untrusted byte data, always decode explicitly if the encoding is non-standard (e.g., cp1251) or remove BOMs before parsing. Use strict=False cautiously for internal data only, as it may introduce security risks. For large files, prefer streaming parsers or chunked reading to avoid memory overload.
Encoding auto-detection: UTF-8, UTF-16, and UTF-32
The json.loads function automatically detects the encoding of input bytes, supporting only UTF-8, UTF-16 (with or without BOM), and UTF-32 (with or without BOM). This mechanism was introduced in version 3.6 and does not require an explicit encoding parameter, which was removed in version 3.9. Automatic encoding detection is based on analysis of the initial bytes:
The module automatically detects UTF-8, UTF-16, and UTF-32 encodings without specifying the internal heuristic. It supports UTF-8, UTF-16 (with or without BOM), and UTF-32 (with or without BOM). If the data does not match these encodings, a UnicodeDecodeError is raised.
2. UTF-16: presence of a BOM (0xFFFE for big-endian or 0xFEFF for little-endian) or analysis of the structure without a BOM.
3. UTF-32: presence of a BOM (0xFFFEFF or 0xFFFFFE) or analysis of the structure without a BOM.
If the data does not match any of these encodings, a UnicodeDecodeError is raised. For example, data in cp1251 or latin-1 will not be recognized automatically.
import json
# Example: UTF-16 with BOM (little-endian)
utf16_payload = b'\xFEFF{ "name": "test" }'
try:
json.loads(utf16_payload)
except ValueError as e:
print(f"ValueError with BOM: {e}")
# Remove BOM and parse
utf16_payload_without_bom = utf16_payload[2:]
data = json.loads(utf16_payload_without_bom)
print(data)json.load with binary file object
json.load reads the entire file content via fp.read() and then parses it, so it does not avoid loading the whole file into memory. This is true even for large files, as the entire content must be read into memory before parsing begins.
json.load(binary_file_object)
This approach is efficient for processing large files because data is read as needed. However, it is important to ensure the file is opened in binary mode ('rb'), not text mode ('r'). Otherwise, an error related to encoding mismatch will occur.
import json
# Пример: чтение бинарного файла
with open('data.json', 'rb') as f:
data = json.load(f)
print(data)UnicodeDecodeError: when data is not UTF-8/16/32
If the input bytes do not match any of the supported encodings (UTF-8, UTF-16, UTF-32), json.loads or json.load will raise a UnicodeDecodeError. This happens because the decoder cannot interpret the bytes as a valid sequence of Unicode characters. For example, data in cp1251 or latin-1 will not be recognized automatically.
To diagnose the problem, use a try-except block and analyze the error message. It usually contains information about the failed decoding attempt and the position where the error occurred. In such cases, you must explicitly decode the bytes to a string with the correct encoding before passing to json.loads.
import json
# Example: data in cp1251 encoding
try:
payload = b'{"name": "test", "value": 42}'
decoded = json.loads(payload)
except UnicodeDecodeError as e:
print(f"UnicodeDecodeError: {e}")
# Explicitly decode with cp1251 before parsing
try:
decoded = json.loads(payload.decode('cp1251'))
print(decoded)
except Exception as inner_e:
print(f"Failed to decode with cp1251: {inner_e}")BOM and its handling
Byte Order Mark (BOM) is a special byte sequence that can indicate the encoding of a file (e.g., UTF-8, UTF-16, or UTF-32). However, RFC 7159 (the JSON standard) prohibits adding a BOM to the start of a JSON text, and the json module in Python strictly follows this rule:
1. The serializer (json.dumps) does not add a BOM to its output.
2. The deserializer (json.loads and json.load) raises a ValueError if it detects a BOM at the beginning of the input, even though RFC permits ignoring it.
This means that if a JSON file contains a BOM, it must be removed manually before passing to json.loads or json.load. For example, for UTF-16 with a BOM, you can use a byte slice: payload[2:] to remove the first two bytes of the BOM.
import json
# Example: handling UTF-16 with BOM
utf16_payload_with_bom = b'\xFEFF{ "name": "test" }'
try:
json.loads(utf16_payload_with_bom)
except ValueError as e:
print(f"ValueError with BOM: {e}")
# Remove BOM and parse
utf16_payload_without_bom = utf16_payload_with_bom[2:]
data = json.loads(utf16_payload_without_bom)
print(data)The strict parameter and control characters in strings
The strict parameter in JSONDecoder (available through json.loads or json.load) controls the handling of control characters inside JSON strings. By default, strict=True, which means control characters (e.g., newline, tab, carriage return) are not allowed inside JSON string values. If a string contains such characters, a JSONDecodeError is raised.
With strict=False, control characters are allowed, which can be useful for internal data where such characters are valid. However, using strict=False for untrusted data may lead to security vulnerabilities, as an attacker could insert control characters to bypass checks.
For example, the string {
log
:
line1
line2
} will be successfully parsed only with strict=False.
import json
# Example: string with control characters
try:
json.loads('{"log": "\nline1\nline2"}') # strict=True (default)
except json.JSONDecodeError as e:
print(f"JSONDecodeError with strict=True: {e}")
try:
json.loads('{"log": "\nline1\nline2"}', strict=False)
print("Successfully parsed with strict=False")
except Exception as e:
print(f"Unexpected error: {e}")Reading bytes from files via pathlib
When working with byte data in json.loads and json.load, consider these key points: 1. Trusted sources: Use automatic encoding detection only for data from trusted sources, as encoding errors can cause application crashes. 2. Non-standard encodings: For data in encodings other than UTF-8/16/32 (e.g., cp1251), explicitly decode bytes to a string with the correct encoding before passing to json.loads. 3. strict parameter: By default, strict=True protects against invalid control characters in strings. Use strict=False only for internal data where such characters are acceptable. 4. BOM: If a file contains a BOM, remove it manually before passing to json.loads, as the module raises a ValueError. 5. Performance: For large files, json.load with a binary file object reads the entire file into memory, so consider alternative approaches like streaming parsers if memory is constrained.
1. Read the file into bytes using Path.read_bytes().
2. Pass the result to json.loads for deserialization.
This approach is equivalent to using json.load with a binary file object, but is more concise and convenient for working with Path objects.
from pathlib import Path
import json
# Пример: чтение байтов через pathlib
path = Path('data.json')
raw_bytes = path.read_bytes()
data = json.loads(raw_bytes)
print(data)Practical recommendations and applicability limits
When working with byte data in json.loads and json.load, consider the following key points:
1. Trusted sources: Use automatic encoding detection only for data from trusted sources, as encoding errors can cause application crashes.
2. Non-standard encodings: For data in encodings other than UTF-8/16/32 (e.g., cp1251), always decode the bytes to a string explicitly with the correct encoding before passing to json.loads.
3. strict parameter: By default, strict=True protects against invalid control characters in strings. Use strict=False only for internal data where such characters are acceptable.
4. BOM: If a file contains a BOM, remove it manually before passing to json.loads, as the module does not handle it automatically.
5. Performance: For large files, prefer json.load with a binary file object, as it reads data as needed without loading the entire file into memory.
Things to check
- Verify that the input data is indeed bytes (bytes or bytearray), not a string.
- Ensure the data is encoded in one of the supported encodings: UTF-8, UTF-16, or UTF-32.
- Use a try-except block to handle UnicodeDecodeError and JSONDecodeError exceptions.
- When working with untrusted sources, always use strict=True (the default).
- For files with a BOM, remove it manually before passing to json.loads.
- If you need to process data in non-standard encodings (e.g., cp1251), decode the bytes to a string explicitly.
- Check that json.load with a binary file object still reads the entire file into memory. For very large files, consider alternative streaming parsers instead of relying on json.load.
- Check that the file is opened in binary mode ('rb') if using json.load.
Where this applies
The main limitations when working with byte data in json.loads and json.load include: 1. Auto-detection only supports UTF-8, UTF-16, and UTF-32. 2. A BOM at the start of the file causes a ValueError. 3. strict=False allows control characters in JSON strings, which may weaken validation. 4. json.load reads the entire file into memory, making it unsuitable for extremely large files without streaming alternatives.