JCS - JSON Canonicalization
Maintained. Last release 3 weeks ago, commits in 4 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install jcsJCS - JSON Canonicalization for Python 3
This is a Python 3 package for a JCS (RFC 8785) compliant JSON canonicalization.
The main author of this code is Anders Rundgren. The original source code is at cyberphone/json-canonicalization including comprehensive test data.
Installation
$ pip install jcs
Using JCS
import jcs
data = jcs.canonicalize({"tag": 4})
Numbers
JCS serializes every JSON number as an IEEE 754 double precision value
(RFC 8785, section 3.1). Python float values
are doubles already and are serialized as is. Python int values have arbitrary precision, so
canonicalize accepts an integer only if a double represents it exactly and its canonical form
reads back as the same integer. It raises a ValueError for any other integer, instead of silently
rounding it:
>>> jcs.canonicalize({"id": 2**53 + 1})
Traceback (most recent call last):
...
ValueError: Integer 9007199254740993 is not exactly representable in canonical JSON ...
Silent rounding would let different values produce identical canonical bytes, so a signature or hash
over one value would also match the other. An accepted integer equals its double, so no other
integer or float shares its canonical bytes, and json.loads reads them back as the same integer.
Keep in mind:
- Canonical JSON writes the shortest digits of the nearest double.
2**60is an exact double, but it serializes as1152921504606847000, a different integer, socanonicalize(2**60)raises.canonicalize(1152921504606847000)raises too, because a double cannot represent it. - From
1e21on, numbers are written with an exponent (10**21becomes1e+21) andjson.loadsreads them asfloat, so every integer that a double represents exactly is accepted.