PyJSON5
repository·main·Indexed 41 days ago
https://github.com/kijewski/pyjson5A high-performance JSON5 serializer and parser for Python 3 written in Cython. It supports JSON5 1.0.0 and standard JSON, providing a drop-in replacement for the built-in json module via load, loads, dump, and dumps. It features specialized encoding functions (encode, encode_bytes, encode_io, encode_callback) that produce ASCII data safe for HTML templates by escaping characters like apostrophes, ampersands, and angle brackets to prevent XSS.
What's inside PyJSON5
- PyJSON5 is a JSON5 serializer and parser library for Python 3, implemented using Cython for performance. It is designed to handle both JSON5 1.0.0 and standard JSON data. The serializer is specifically designed to produce ASCII data that is safe for use within HTML templates by encoding characters like apostrophes, ampersands, and angle brackets as unicode escaped sequences.
Understand PyJSON5 performance characteristics
mainPyJSON5 is implemented in Cython to provide performance superior to pure-Python implementations.
Decoder Performance
When processing pure JSON data,
pyjson5.decodeperforms at speeds comparable to the standard Pythonjsonmodule.Encoder Performance
The encoder is optimized for producing XML-safe output. It ensures that the serialized data contains no chevrons (
<>), ampersands (&), apostrophes ('), or control characters.Key encoder behaviors:
- Pure JSON Compatibility: If the input contains no
NaNor infinite values, the output is valid pure JSON. - ASCII Output: Regardless of whether you use
pyjson5.encodeorpyjson5.encode_bytes, the output is always ASCII. - XML Safety: The output is automatically escaped for XML safety, making it faster than a combination of
json.dumpsandxml.sax.saxutils.escape.
- Pure JSON Compatibility: If the input contains no
HTML-safe JSON5 serialization
mainThe
pyjson5serializer produces ASCII data specifically designed to be safe for use within HTML templates. It automatically encodes apostrophes ('), ampersands (&), greater-than (>), and less-than (<) signs as Unicode escaped sequences. This prevents common injection issues when embedding data in HTML attributes or scripts.Note: Unless the input contains
InfinityorNaNvalues, the output is guaranteed to be valid standardJSON(RFC 8259)."<a onclick='alert(" + encode(data) + ")'>show message</a>"Install pyjson5 via pip
mainInstall the
pyjson5library usingpipto enable JSON5 serialization and parsing in your Python project.$ pip install pyjson5Encode data for safe HTML usage
mainThe
pyjson5.encodefunction returns ASCII data specifically designed to be safe for use within HTML templates. It automatically encodes apostrophes ('), ampersands (&), greater-than (>), and less-than (<) signs as Unicode escaped sequences. This prevents XSS or syntax errors when injecting JSON data into HTML attributes or script tags.Note: The resulting output is valid JSON (RFC 8259) as long as the input does not contain
InfinityorNaNvalues."<a onclick='alert(" + encode(data) + ")'>show message</a>"Use PyJSON5 as a drop-in replacement for the json module
mainPyJSON5 providesload(),loads(),dump(), anddumps()functions that mirror the API of Python's built-injsonmodule. This allows you to swapimport jsonwithimport pyjson5in many existing workflows. However, for the intended specialized behavior (like HTML-safe encoding), you should use theencode_*()anddecode_*()functions instead.Decode JSON5 data using pyjson5.decode
mainUse
pyjson5.decodeto parse valid JSON5 1.0.0 and standard JSON data. This function is the primary entry point for converting JSON5 strings or data into Python objects. It supports all valid JSON5 syntax unless the nesting level is excessively high.import pyjson5 data = pyjson5.decode('{\n key: "value",\n // comment\n}')Serialize to JSON-compatible formats with dump and dumps
mainFor standard JSON compatibility (rather than HTML-safe encoding), use the following functions:
pyjson5.dumps(obj): Returns a JSON-compatible string.pyjson5.dump(obj, fp): Writes a JSON-compatible representation to a file-like objectfp.
Use encode_*() for HTML-safe serialization
mainTo generate JSON strings that are safe to embed directly into HTML attributes or templates, use the
encode_*()functions. These functions encode apostrophes ('), ampersands (&), greater-than (>), and less-than (<) signs as unicode escaped sequences. This prevents XSS or syntax errors when injecting data into JavaScript contexts within HTML.# Example of safe embedding in an HTML template # "<a onclick='alert(" + encode(data) + ")'>show message</a>"Use load and loads for JSON compatibility
mainIf you are migrating from the standard
jsonmodule or require compatibility with standard JSON patterns, use these functions:pyjson5.load(fp): Reads JSON5 data from a file-like objectfp.pyjson5.loads(s): Parses a JSON5 strings.
import pyjson5 # Parsing a string data = pyjson5.loads('{\n name: "example"\n}') # Parsing from a file with open('config.json5', 'r') as f: data = pyjson5.load(f)Use pyjson5 encoding functions
mainPyJSON5 provides several ways to serialize data depending on your required output format (string, bytes, stream, or callback):
pyjson5.encode(obj): Returns an ASCII string safe for HTML.pyjson5.encode_bytes(obj): Returns encoded bytes.pyjson5.encode_io(obj, io): Writes encoded data directly to an I/O stream.pyjson5.encode_callback(obj, callback): Uses a callback function for the encoding process.pyjson5.encode_noop(obj): A no-op encoder (typically used for testing or as a placeholder).
Decode JSON5 from various input sources
mainPyJSON5 provides specialized decoding functions depending on the input type:
pyjson5.decode_latin1: Decodes data using the latin1 encoding.pyjson5.decode_buffer: Decodes from a buffer/bytes-like object.pyjson5.decode_callback: Decodes using a callback mechanism.pyjson5.decode_io: Decodes from an I/O stream (file-like object).