JCS - JSON Canonicalization
JCS (JSON Canonicalization Scheme) for Python 3 is a library that provides RFC 8785 compliant JSON canonicalization. It ensures a deterministic representation of JSON data, crucial for cryptographic operations like hashing and signing where data integrity and consistent serialization are paramount. The current version is 0.2.1, released on April 10, 2022. The project appears to have a stable, though not rapid, release cadence.
Warnings
- gotcha Floating-point number representation in JCS (RFC 8785) can be subtly different from standard float-to-string conversions in some languages. While `jcs` aims for compliance, users should be aware of potential discrepancies when comparing canonicalized output across different language implementations or with specific test vectors, as precision issues or specific formatting rules (e.g., for `1e+23` vs `1.0e23`) might arise depending on the underlying float implementation.
- gotcha The library expects Python data structures that are directly convertible to JSON (dictionaries, lists, strings, numbers, booleans, and `None`). Passing non-standard Python objects or custom classes that are not implicitly JSON-serializable will result in `TypeError` or unexpected output during canonicalization.
- gotcha This Python 'jcs' library for JSON canonicalization is entirely distinct from the 'jcs' module used within Juniper Junos OS for network device automation scripts. Searching for 'python jcs' might yield results related to the Juniper module, leading to confusion.
- gotcha While not explicitly documented for the Python version, a related Elixir implementation of JCS (based on this Python package) notes that its JSON encoding 'is probably orders of magnitude slower than the Jason library' due to sorting object properties based on UTF-16 encoded keys. This suggests that `jcs` might not be optimized for extreme performance on very large JSON structures.
Install
-
pip install jcs
Imports
- canonicalize
import jcs canonical_json = jcs.canonicalize(data)
Quickstart
import jcs
data_to_canonicalize = {
"name": "Alice",
"age": 30,
"isStudent": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"zip": "12345"
}
}
canonical_json = jcs.canonicalize(data_to_canonicalize)
print(canonical_json)