canonicalizeToBytes

import { canonicalizeToBytes } from "jsr:@ende/json";

function

function canonicalizeToBytes(value: JsonValue): Uint8Array_

Serializes a JSON value to canonical UTF-8 bytes per RFC 8785 JSON Canonicalization Scheme (JCS).

This is equivalent to new TextEncoder().encode(canonicalize(value)) and is provided as a convenience for cryptographic operations that require byte input.

value: JsonValue

The JSON value to canonicalize.

Returns

The canonical JSON as UTF-8 bytes.

Example: Creating a verifiable hash

import { canonicalizeToBytes } from "@ende/json/canonicalize";
import { encodeHex } from "@ende/encoding/hex";
import { assertEquals } from "@ende/assert";

async function sha256Hex(data: Uint8Array): Promise<string> {
  const hash = await crypto.subtle.digest("SHA-256", data.buffer as ArrayBuffer);
  return encodeHex(new Uint8Array(hash));
}

// Create a deterministic hash of JSON data for verification
const payload = { action: "transfer", amount: 100, to: "alice" };
const hash = await sha256Hex(canonicalizeToBytes(payload));

// Same hash regardless of original key order
const reordered = { to: "alice", action: "transfer", amount: 100 };
const reorderedHash = await sha256Hex(canonicalizeToBytes(reordered));

assertEquals(hash, reorderedHash);

See also

Source