pyjson5
PyJSON5 is a high-performance JSON5 serializer and parser library for Python 3, implemented in Cython. It extends the standard JSON format with features like comments, unquoted keys, and trailing commas, making it ideal for human-editable configuration files. This library is actively maintained, with frequent updates and a current stable version of 2.0.0.
Warnings
- breaking In `pyjson5` v2.0.0, the `dump()` function now consistently writes `str` (Unicode) instead of `bytes` to file-like objects. This is a change from previous versions and can lead to `TypeError: a bytes-like object is required, not 'str'` if the target file object is opened in binary write mode (`'wb'`).
- breaking Starting with `pyjson5` v2.0.0, the library explicitly requires Python 3.8 or later. Versions prior to `v1.6.8` supported Python 3.5+, and `v1.6.8` raised the minimum to Python 3.7+.
- gotcha Unlike Python's standard `json` module, `pyjson5` does not support the `cls` keyword argument for custom `JSONDecoder` or `JSONEncoder` subclasses in its `load`, `loads`, `dump`, or `dumps` functions. This is due to its Cython-based parsing and serialization approach.
- gotcha JSON5 is designed for human-editable configuration files, allowing features like comments and unquoted keys. It is generally not recommended for strict machine-to-machine communication, where the more rigid standard JSON format is often preferred due to broader tooling support and stricter validation.
- gotcha By default, `pyjson5.load()` and `pyjson5.loads()` allow duplicate keys within an object (dictionary) in the JSON5 input. When duplicate keys are present, the last encountered value for that key will override previous ones.
Install
-
pip install pyjson5
Imports
- loads, dumps, load, dump
import pyjson5 # Use pyjson5.loads, pyjson5.dumps, etc.
Quickstart
import pyjson5
import io
json5_data = """
{
// This is a comment
name: 'Project Alpha',
version: 1.0.0,
features: [
'comments',
'trailing commas',
],
config: { key: 'value', }, // Trailing comma
}
"""
# Load from a string
data = pyjson5.loads(json5_data)
print(f"Loaded data: {data}")
# Dump to a string
output_json5 = pyjson5.dumps(data, indent=2)
print(f"\nDumped JSON5:\n{output_json5}")
# Load from a file-like object (StringIO acts like a file)
file_like_obj_read = io.StringIO(json5_data)
file_data = pyjson5.load(file_like_obj_read)
print(f"\nLoaded from file-like object: {file_data}")
# Dump to a file-like object
file_like_obj_write = io.StringIO()
pyjson5.dump(data, file_like_obj_write, indent=2)
print(f"\nDumped to file-like object:\n{file_like_obj_write.getvalue()}")