JSON5 for Python
The `json5` library is a Python implementation of the JSON5 data format, which extends standard JSON to be more human-friendly, allowing features like JavaScript-style comments, unquoted object keys, trailing commas in objects and arrays, and single-quoted or multi-line strings. It aims to mirror the API of Python's built-in `json` module for ease of use. The current version is 0.14.0, and it maintains a regular release cadence.
Common errors
-
ModuleNotFoundError: No module named 'json5'
cause The `json5` Python package is not installed in the current environment.fixInstall the `json5` library using pip: `pip install json5`. -
json5.json5.Json5DecodeError: Unexpected token
cause The input JSON5 string contains a syntax error that even the more lenient JSON5 parser cannot handle, such as a malformed structure, an invalid unquoted key, or an unexpected character.fixReview the JSON5 string for syntax errors. Ensure that unquoted keys are valid JavaScript identifiers, and check for missing commas, unclosed strings, or other structural issues. -
json5.json5.Json5DecodeError: Invalid control character at: line X column Y (char Z)
cause The JSON5 input string contains unescaped control characters (e.g., raw newline, tab, or carriage return characters) within a string literal that must be escaped.fixReplace unescaped control characters within string literals with their corresponding JSON escape sequences (e.g., `\n` for newline, `\t` for tab, `\r` for carriage return).
Warnings
- gotcha Performance Warning: `json5` is significantly slower than Python's built-in `json` module (especially the C-optimized version). It can be 1000-6000x slower for parsing and 200x slower than the pure Python `json` module. Consider performance implications for high-throughput applications.
- breaking Unsupported `cls` argument: The `cls` keyword argument, commonly used in `json.load()`, `json.loads()`, `json.dump()`, and `json.dumps()` for custom `JSONDecoder` or `JSONEncoder` subclasses, is not supported by `json5` due to a different parsing approach.
- gotcha Encoding in `dump()` is ignored: The `encoding` method to `dump()` is ignored, and unicode strings are always returned. This differs from the behavior of the standard `json` module.
- gotcha Duplicate keys handling: By default, `json5.load()` and `json5.loads()` allow duplicate object keys, with the last key-value pair taking precedence (standard JSON behavior). However, you can explicitly reject duplicates by passing `allow_duplicate_keys=False`. This is a notable difference in explicit control compared to the standard `json` module.
- gotcha Not a full JavaScript parser: The `json5` library is designed to parse JSON5 documents, not arbitrary JavaScript code. Attempting to parse non-JSON5 JavaScript syntax (e.g., bare integers as object keys, or complex expressions) will result in parsing errors.
Install
-
pip install json5
Imports
- json5
import json5
Quickstart
import json5
# Parse a JSON5 string with comments and trailing commas
config_string = """
{
// Application settings
name: 'my-app',
version: '1.0.0',
features: [
'comments',
'trailing commas',
],
}
"""
config = json5.loads(config_string)
print(f"App Name: {config['name']}")
# Convert a Python object to a JSON5 string
data = {
'name': 'another-app',
'debug': True,
'ports': [3000, 3001],
}
json5_string = json5.dumps(data, indent=2, quote_keys=False, trailing_commas=True)
print("\nSerialized JSON5:")
print(json5_string)
# Example of reading/writing a file (assuming a config.json5 exists)
# with open('config.json5', 'w') as f:
# json5.dump(data, f, indent=2)
#
# with open('config.json5', 'r') as f:
# loaded_config = json5.load(f)
# print(f"\nLoaded from file: {loaded_config['name']}")