JSON 18 ๐ Canonical JSON and Deterministic Serialization
Canonical JSON is the answer to a question that standard JSON deliberately leaves open: if two systems have the same logical data, do they produce the same bytes when they serialize it? The RFC 8259 does not require the object members to be in any order, does not require the numbers to be in any particular notation, and does not require the whitespace to be absent. Two serializers can produce the different byte sequences for the same object, and the difference is the problem when the bytes are hashed, signed, or compared. Canonical JSON is the profile that removes the variability: the members are sorted, the numbers are normalized, the strings are escaped minimally, and the whitespace is removed. The result is the deterministic byte sequence that the cryptographic operations require.
The current standard is the RFC 8785, the JSON Canonicalization Scheme (JCS), published in June 2020. The scheme specifies the member ordering by the UTF-16 code units, the number serialization according to the ECMAScript Number::toString algorithm, the minimal string escaping, and the rejection of the duplicate keys and the invalid values . The JCS is not the only canonicalization scheme, but it is the one with the public specification and the cross-implementation test vectors, and it is the basis for the JSON Web Signature (JWS) and the other crypto formats that need the deterministic serialization.
Key point: Canonical JSON is the deterministic byte sequence for the same logical data. The RFC 8785 JCS sorts the object members by the UTF-16 code units, serializes the numbers as the ECMAScript Number::toString, escapes the strings minimally, and rejects the duplicate keys, the NaN, the Infinity, and the unpaired surrogates. The JCS is the standard for the cryptographic hashing and signing, and the canonical bytes are the input to the hash or the signature.
Why canonical JSON exists
The determinism problem. A cryptographic signature is computed over the bytes, and the verifier recomputes the signature over the bytes it receives. If the sender and the receiver serialize the same logical object differently, the bytes differ, and the signature verification fails even though the data is identical. The canonicalization is the mechanism that makes the bytes the same regardless of the serializer, the platform, and the field order .
The sorting problem. The JSON object is the unordered collection, and the serializers are free to emit the members in any order. The JCS sorts the members by the UTF-16 code units, and the sorting is the mechanism that removes the order variability . The UTF-16 code unit order is not the same as the byte order for the code points above the basic multilingual plane, and the distinction is the reason the JCS specifies the UTF-16 and not the UTF-8 byte order.
The number problem. The JSON number is the arbitrary-precision decimal, and the serializers are free to emit the 1e2, the 100, or the 100.0 for the same value. The JCS parses the number to the IEEE 754 double and re-serializes it according to the ECMAScript Number::toString, and the re-serialization is the mechanism that produces the single representation . The 1e21 becomes "1e+21", the 1e-7 becomes "1e-7", and the -0 becomes "0" .
The escape problem. The JSON string can escape the characters that do not need the escaping, and the serializers are free to emit the \u0041 or the A for the same character. The JCS requires the minimal escape set: the quote, the backslash, and the control characters from the U+0000 to the U+001F. The other characters are emitted as the literal UTF-8 . The minimal set is the mechanism that produces the single representation.
The duplicate problem. The JSON grammar allows the duplicate keys, and the behavior is undefined. The JCS requires the duplicate keys to be rejected, and the rejection is the mechanism that prevents the ambiguity . The duplicate is the security hazard, because the different parsers can resolve it differently.
a. The JCS rules and the number serialization
The JCS is defined by the RFC 8785, and the rules are the member sorting, the number serialization, the string escaping, and the validation. The member sorting is the recursive UTF-16 code unit order, and the sorting is applied to every object at every depth .
// The member sorting
// The object: { "b": 2, "a": 1 }
// The canonical: {"a":1,"b":2}
// The nested object: { "c": { "y": 3, "x": 2 }, "a": 1 }
// The canonical: {"a":1,"c":{"x":2,"y":3}}
The number serialization is the ECMAScript Number::toString algorithm. The JCS parses the number to the IEEE 754 double, and the double is the value that the serialization represents . The integers beyond the 2^53 lose the precision, and the RFC recommends the large integers to be carried as the strings .
// The number serialization
// The input: 1e21
// The canonical: 1e+21
// The input: 1e-7
// The canonical: 1e-7
// The input: -0
// The canonical: 0
// The input: 100
// The canonical: 100
The -0 is the special case. The ECMAScript Number::toString returns the "0" for both the +0 and the -0, and the JCS follows the same rule . The RFC notes that the -0 is the valid JSON number but is serialized as 0, and the parser should generate the error when it encounters the -0 to thwart the potential attacks . The distinction is the mechanism that keeps the canonical output stable.
The string escaping is the minimal set. The quote, the backslash, and the control characters from the U+0000 to the U+001F are escaped. The other characters are the literal UTF-8, and the non-ASCII is not escaped . The minimal set is the mechanism that produces the single representation.
// The string escaping
// The input: "he\"llo\n"
// The canonical: "he\"llo\n"
// The input: "๐"
// The canonical: "๐" (the literal UTF-8)
The JCS rejects the duplicate keys, the NaN, the Infinity, the unpaired surrogates, the invalid UTF-8, and the control characters in the strings . The rejection is the mechanism that keeps the canonical input valid, and the validation is the reason the canonicalizer is the strict parser.
b. The implementations and the test vectors
The JCS is implemented in the multiple languages, and the implementations are the mechanism that produces the canonical bytes in the different environments. The Go package jcs is the standard library only implementation, and it canonicalizes the raw JSON bytes with the strict parsing . The Go package agentsession/internal/jcs implements the same scheme with the FormatNumber and the LessUTF16 helpers . The Dart package transaction_intent_signer implements the canonicalization with the sorted keys and the preserved arrays . The JavaScript package @peac/crypto implements the JCS with the parity tests against the Go implementation .
// The Go JCS canonicalization
import "github.com/DonaldMurillo/gofastr/core/jcs"
// The canonicalization of the raw JSON bytes.
canonical, err := jcs.CanonicalizeJSON([]byte(`{"b":2,"a":1}`))
// canonical: {"a":1,"b":2}
The test vectors are the mechanism that proves the implementations agree. The agent-passport-system repository has the 10 frozen test vectors that cover the nulls, the Unicode key ordering, the empty containers, the deep nesting, the string escapes, the number edge cases, and the realistic receipt shapes . The PEAC repository has the extended parity corpus that covers the Unicode normalization, the surrogate pairs, and the escape sequences . The vectors are the mechanism that lets the different implementations prove the byte-identical output before the exchange.
// The test vector verification
// The input: { "b": 2, "a": 1 }
// The canonical bytes hex: 7b2261223a312c2262223a327d
// The canonical string: {"a":1,"b":2}
// The SHA-256: the hash of the canonical bytes
The JCS is not the only canonicalization scheme. The QOS canonical JSON is the variant that normalizes the integer numbers to the base-10 integer strings and rejects the non-integers . The EL-C14N-v2 is the scheme that sorts the keys by the ASCII code point and prepends the domain tag . The variants are the mechanism that adapts the canonicalization to the specific protocol, and the choice is the protocol’s specification.
Complete Example Session
// ============================================
// PART 1: THE BASIC CANONICALIZATION
// ============================================
// The input object
const input = { b: 2, a: 1 };
// The canonical output
// {"a":1,"b":2}
// The members are sorted by the UTF-16 code units.
// ============================================
// PART 2: THE NESTED OBJECT
// ============================================
// The input: { c: { y: 3, x: 2 }, a: 1 }
// The canonical: {"a":1,"c":{"x":2,"y":3}}
// The sorting is recursive.
// ============================================
// PART 3: THE NUMBER SERIALIZATION
// ============================================
// The input: 1e21
// The canonical: 1e+21
// The input: 1e-7
// The canonical: 1e-7
// The input: -0
// The canonical: 0
// ============================================
// PART 4: THE STRING ESCAPING
// ============================================
// The input: "he\"llo\n"
// The canonical: "he\"llo\n"
// The input: "๐"
// The canonical: "๐" (the literal UTF-8)
// ============================================
// PART 5: THE DUPLICATE KEY REJECTION
// ============================================
// The input: {"a":1,"a":2}
// The error: the duplicate key
// ============================================
// PART 6: THE VALIDATION
// ============================================
// The invalid inputs:
// NaN, Infinity, -Infinity
// The unpaired surrogates
// The invalid UTF-8
// The control characters in the strings
// ============================================
// PART 7: THE HASHING
// ============================================
// The canonical bytes are the input to the hash.
const canonicalBytes = new TextEncoder().encode(canonicalString);
const hash = await crypto.subtle.digest("SHA-256", canonicalBytes);
// The hash is the same for the same logical object.
// ============================================
// PART 8: THE SIGNING
// ============================================
// The canonical bytes are the input to the signature.
// The Ed25519 signs the canonical bytes.
const signature = ed25519.sign(canonicalBytes, privateKey);
// The verifier recomputes the canonical bytes and verifies.
// ============================================
// PART 9: THE IMPLEMENTATION
// ============================================
import { canonicalize } from "@peac/crypto";
const canonical = canonicalize({ b: 2, a: 1 });
// {"a":1,"b":2}
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The members are sorted by the UTF-16 code units.
// [ ] The numbers are the ECMAScript Number::toString.
// [ ] The strings are the minimal escapes.
// [ ] The duplicate keys are rejected.
// [ ] The NaN and the Infinity are rejected.
// [ ] The canonical bytes are the hash input.
The ten parts covered the basic canonicalization, the nested object, the number serialization, the string escaping, the duplicate key rejection, the validation, the hashing, the signing, the implementation, and the checklist. The through-line is that the canonicalization is the determinism, and the determinism is the hash and the signature.
Quick Reference
The JCS rules
| Rule | Detail |
|---|---|
| The member sorting | The UTF-16 code unit order, recursive |
| The number serialization | The ECMAScript Number::toString |
| The string escaping | The minimal set: the quote, the backslash, the control characters |
| The duplicate keys | The rejected |
| The NaN and the Infinity | The rejected |
| The unpaired surrogates | The rejected |
The number edge cases
| Input | Canonical |
|---|---|
1e21 | 1e+21 |
1e-7 | 1e-7 |
-0 | 0 |
100 | 100 |
The implementations
| Language | Package | Notes |
|---|---|---|
| Go | jcs | The standard library only |
| Go | agentsession/internal/jcs | The FormatNumber and the LessUTF16 |
| Dart | transaction_intent_signer | The sorted keys |
| JavaScript | @peac/crypto | The parity tests |
The canonicalization variants
| Scheme | Difference |
|---|---|
| The RFC 8785 JCS | The standard |
| The QOS canonical JSON | The integer strings, the non-integers rejected |
| The EL-C14N-v2 | The ASCII sort, the domain tag |
Best Practices
โ Do This:
// Use the JCS canonicalization before the hashing
const canonical = canonicalize(data); // โ
// Use the canonical bytes for the signature
const signature = sign(canonicalBytes); // โ
// Reject the duplicate keys
// The JCS canonicalizer rejects them. // โ
โ Don’t Do This:
// Use the JSON.stringify for the hashing
const hash = sha256(JSON.stringify(data)); // the order and the number vary // โ
// Assume the -0 and the 0 are different
// The JCS serializes both as "0". // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The signature fails | The serializer is not canonical | Use the JCS canonicalization |
| The hash differs between the platforms | The number serialization differs | Use the ECMAScript Number::toString |
| The duplicate keys are accepted | The parser is lenient | Use the strict canonicalizer |
| The large integer loses precision | The IEEE 754 double | Carry the large integers as the strings |
Real-World Examples
1. The basic canonicalization
canonicalize({ b: 2, a: 1 }); // {"a":1,"b":2}
2. The nested object
canonicalize({ c: { y: 3, x: 2 }, a: 1 }); // {"a":1,"c":{"x":2,"y":3}}
3. The number
canonicalize(1e21); // 1e+21
4. The negative zero
canonicalize(-0); // 0
5. The literal UTF-8
canonicalize("๐"); // "๐"
6. The duplicate rejection
canonicalize('{"a":1,"a":2}'); // the error
7. The hashing
sha256(canonicalize(data));
8. The signing
ed25519.sign(canonicalize(data), privateKey);
9. The Go implementation
jcs.CanonicalizeJSON([]byte(`{"b":2,"a":1}`))
10. The test vector
// The canonical bytes hex: 7b2261223a312c2262223a327d
Visual
The Canonicalization Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE CANONICALIZATION FLOW โ
โ โ
โ The JSON object โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The JCS โ Sort, normalize, escape โ
โ โ canonicalizer โ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The canonical bytes โ The deterministic sequence โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The hash or the โ The same for the same data โ
โ โ signature โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Member Sorting
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE MEMBER SORTING โ
โ โ
โ The input: { "b": 2, "a": 1 } โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Sort by the UTF-16 โ The "a" before the "b" โ
โ โ code units โ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ The output: {"a":1,"b":2} โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Number Serialization
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE NUMBER SERIALIZATION โ
โ โ
โ The input: 1e21 โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The ECMAScript โ The Number::toString โ
โ โ algorithm โ โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ The output: 1e+21 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| The standard | The RFC 8785 JCS |
| The member sorting | The UTF-16 code units, recursive |
| The number serialization | The ECMAScript Number::toString |
| The string escaping | The minimal set |
| The duplicate keys | The rejected |
The -0 | The 0 |
| The canonical bytes | The hash and the signature input |
Key takeaways:
- The canonical JSON is the deterministic byte sequence for the same logical data. The standard JSON does not require the member order, the number notation, or the whitespace to be consistent, and the canonicalization is the mechanism that removes the variability .
- The RFC 8785 JCS sorts the members by the UTF-16 code units. The sorting is recursive, and the UTF-16 code unit order is not the same as the byte order for the code points above the basic multilingual plane . The sorting is the mechanism that makes the member order deterministic.
- The number serialization is the ECMAScript
Number::toString. The1e21becomes the1e+21, the1e-7becomes the1e-7, and the-0becomes the0. The large integers beyond the 2^53 lose the precision, and the RFC recommends the strings . - The duplicate keys, the NaN, the Infinity, and the unpaired surrogates are rejected. The rejection is the mechanism that keeps the canonical input valid, and the validation is the reason the canonicalizer is the strict parser .
- The canonical bytes are the input to the hash and the signature. The determinism is the mechanism that makes the signature verification work across the platforms and the serializers, and the test vectors are the mechanism that proves the implementations agree .
Remember: The canonical JSON is the deterministic serialization for the cryptographic operations. The RFC 8785 JCS is the standard, and the rules are the UTF-16 member sorting, the ECMAScript number serialization, the minimal string escaping, and the strict validation. The canonical bytes are the hash and the signature input, and the determinism is the mechanism that makes the verification work.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!