| | |

JSON 18 ๐Ÿ“„ Canonical JSON and Deterministic Serialization

โฑ๏ธ Estimated read: 12 min | |

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

RuleDetail
The member sortingThe UTF-16 code unit order, recursive
The number serializationThe ECMAScript Number::toString
The string escapingThe minimal set: the quote, the backslash, the control characters
The duplicate keysThe rejected
The NaN and the InfinityThe rejected
The unpaired surrogatesThe rejected

The number edge cases

InputCanonical
1e211e+21
1e-71e-7
-00
100100

The implementations

LanguagePackageNotes
GojcsThe standard library only
Goagentsession/internal/jcsThe FormatNumber and the LessUTF16
Darttransaction_intent_signerThe sorted keys
JavaScript@peac/cryptoThe parity tests

The canonicalization variants

SchemeDifference
The RFC 8785 JCSThe standard
The QOS canonical JSONThe integer strings, the non-integers rejected
The EL-C14N-v2The 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

PitfallWhy It HappensFix
The signature failsThe serializer is not canonicalUse the JCS canonicalization
The hash differs between the platformsThe number serialization differsUse the ECMAScript Number::toString
The duplicate keys are acceptedThe parser is lenientUse the strict canonicalizer
The large integer loses precisionThe IEEE 754 doubleCarry 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

ItemValue
The standardThe RFC 8785 JCS
The member sortingThe UTF-16 code units, recursive
The number serializationThe ECMAScript Number::toString
The string escapingThe minimal set
The duplicate keysThe rejected
The -0The 0
The canonical bytesThe 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. The 1e21 becomes the 1e+21, the 1e-7 becomes the 1e-7, and the -0 becomes the 0 . 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.

Was this helpful?


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!