### Install rfc8785 library Source: https://github.com/trailofbits/rfc8785.py/blob/main/README.md Command to install the rfc8785 package using pip. ```bash python -m pip install rfc8785 ``` -------------------------------- ### Serialize to I/O stream Source: https://github.com/trailofbits/rfc8785.py/blob/main/README.md Demonstrates how to use rfc8785.dump to write canonicalized JSON directly to a file-like object. ```python import rfc8785 with open("/some/file", mode="wb") as io: rfc8785.dump([1, 2, 3, 4], io) ``` -------------------------------- ### Handling Numeric Domain Constraints in RFC 8785 Source: https://context7.com/trailofbits/rfc8785.py/llms.txt Demonstrates how the library handles integer and float constraints. It shows how values outside the safe integer range or invalid floats like NaN and infinity trigger specific domain errors. ```python import rfc8785 import math # Integer domain handling min_safe = -(2**53) + 1 result = rfc8785.dumps(min_safe) try: rfc8785.dumps(2**53) except rfc8785.IntegerDomainError as e: print(f"Error: {e}") # Float domain handling try: rfc8785.dumps(float("nan")) except rfc8785.FloatDomainError as e: print(f"Error: {e}") ``` -------------------------------- ### Implementing UTF-16BE Key Sorting Source: https://context7.com/trailofbits/rfc8785.py/llms.txt Illustrates the canonical key sorting mechanism required by RFC 8785. Keys are sorted by their UTF-16BE encoding to ensure cross-platform consistency, which differs from standard ASCII sorting. ```python import rfc8785 import json data = { "": "empty", "1": {"f": {"F": 5, "f": "hi"}, "\n": 56}, "10": {}, "111": [{"E": "no", "e": "yes"}], "A": {}, "a": {} } # Canonical serialization canonical = rfc8785.dumps(data) # Verify consistency parsed = json.loads(canonical) assert rfc8785.dumps(parsed) == canonical ``` -------------------------------- ### Handle Canonicalization Errors Source: https://context7.com/trailofbits/rfc8785.py/llms.txt Demonstrates how to catch CanonicalizationError and its subclasses to handle invalid input types, non-string keys, or non-UTF-8 codepoints during serialization. ```python import rfc8785 def safe_canonicalize(data): try: return rfc8785.dumps(data) except rfc8785.CanonicalizationError as e: print(f"Canonicalization failed: {e}") return None safe_canonicalize({1: "value", None: "another"}) safe_canonicalize({1, 2, 3}) safe_canonicalize("\udead") ``` -------------------------------- ### Canonicalize JSON data Source: https://github.com/trailofbits/rfc8785.py/blob/main/README.md Demonstrates how to use rfc8785.dumps to convert a Python dictionary into a canonicalized UTF-8 encoded bytes object. ```python import rfc8785 foo = { "key": "value", "another-key": 2, "a-third": [1, 2, 3, [4], (5, 6, "this works too")], "more": [None, True, False], } rfc8785.dumps(foo) ``` -------------------------------- ### rfc8785.dump Source: https://github.com/trailofbits/rfc8785.py/blob/main/README.md Serializes a Python object directly to a binary I/O stream. ```APIDOC ## rfc8785.dump(obj, fp) ### Description Serializes a Python object into canonical JSON and writes it directly to the provided file-like object. ### Parameters - **obj** (Any) - Required - The object to serialize. - **fp** (BinaryIO) - Required - A file-like object opened in binary mode ('wb'). ### Request Example ```python import rfc8785 with open("output.json", mode="wb") as io: rfc8785.dump([1, 2, 3], io) ``` ### Response - **Returns** (None) - Writes directly to the stream. ### Error Handling - Raises `rfc8785.CanonicalizationError` if serialization fails. ``` -------------------------------- ### Validate Integer Range with IntegerDomainError Source: https://context7.com/trailofbits/rfc8785.py/llms.txt Shows how the library enforces IEEE 754 safe integer limits to prevent precision loss, raising IntegerDomainError for values outside the range of -(2^53 - 1) to 2^53 - 1. ```python import rfc8785 max_safe = 2**53 - 1 result = rfc8785.dumps(max_safe) ``` -------------------------------- ### Serialize Object to Stream with dump Source: https://context7.com/trailofbits/rfc8785.py/llms.txt The dump() function writes canonical JSON directly to a binary I/O stream, which is memory-efficient for large objects. It is commonly used for generating deterministic hashes of JSON payloads. ```python import rfc8785 import hashlib from io import BytesIO with open("/tmp/canonical.json", mode="wb") as f: rfc8785.dump({"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}, f) buffer = BytesIO() rfc8785.dump([1, 2, 3, 4], buffer) buffer = BytesIO() rfc8785.dump({"payload": "sensitive-data", "timestamp": 1699999999}, buffer) canonical = buffer.getvalue() digest = hashlib.sha256(canonical).hexdigest() ``` -------------------------------- ### rfc8785.dumps Source: https://github.com/trailofbits/rfc8785.py/blob/main/README.md Serializes a Python object into a canonical JSON byte string. ```APIDOC ## rfc8785.dumps(obj) ### Description Serializes a Python object into a canonical JSON byte string as defined by RFC 8785. The output is always minimally encoded and returned as a bytes object. ### Parameters - **obj** (Any) - Required - The Python object (dict, list, etc.) to canonicalize. Note that dictionary keys must be strings. ### Request Example ```python import rfc8785 foo = {"key": "value", "another-key": 2} rfc8785.dumps(foo) ``` ### Response - **Returns** (bytes) - The canonicalized JSON representation. ### Error Handling - Raises `rfc8785.CanonicalizationError` if serialization fails. ``` -------------------------------- ### Serialize Object to Canonical JSON Bytes with dumps Source: https://context7.com/trailofbits/rfc8785.py/llms.txt The dumps() function converts Python objects into canonical UTF-8 encoded bytes. It handles nested structures, sorts dictionary keys by UTF-16BE encoding, and enforces ECMA-262 number formatting. ```python import rfc8785 from enum import IntEnum data = { "key": "value", "another-key": 2, "a-third": [1, 2, 3, [4], (5, 6, "this works too")], "more": [None, True, False], } result = rfc8785.dumps(data) sorted_example = {"A": {}, "a": {}, "1": {"f": {"F": 5, "f": "hi"}}} result = rfc8785.dumps(sorted_example) float_data = {"small": 0.000001, "large": 9007199254740992, "precise": 333333333.33333325} result = rfc8785.dumps(float_data) class Status(IntEnum): PENDING = 1 ACTIVE = 2 COMPLETE = 3 result = rfc8785.dumps({"status": Status.ACTIVE}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.