@stryke/json
Version:
A package containing JSON parsing/stringify utilities used by Storm Software.
28 lines (27 loc) • 1.57 kB
JavaScript
//#region src/canonical.ts
/**
* Converts a JavaScript value to a canonical JSON string representation. This function is used for signing JSON objects in a consistent way, ensuring that the same input will always produce the same output string. The canonicalization process includes:
* - Sorting object keys in lexicographical order.
* - Removing whitespace and line breaks.
* - Representing primitive values (null, boolean, number, string) in their standard JSON format.
* - Recursively applying these rules to nested objects and arrays.
*
* This function is designed to produce a deterministic string representation of a JSON value, which is essential for cryptographic signing and verification processes where the exact byte representation of the data must be consistent across different environments and implementations.
*
* @param obj - The JavaScript value to convert to a canonical JSON string.
* @returns A canonical JSON string representation of the input value.
*/
function canonicalJson(obj) {
if (obj === null || obj === void 0) return "null";
if (typeof obj === "boolean" || typeof obj === "number") return JSON.stringify(obj);
if (typeof obj === "string") return JSON.stringify(obj);
if (Array.isArray(obj)) return `[${obj.map((item) => canonicalJson(item)).join(",")}]`;
if (typeof obj === "object") return `{${Object.keys(obj).sort().map((key) => {
const value = canonicalJson(obj[key]);
return `${JSON.stringify(key)}:${value}`;
}).join(",")}}`;
return "null";
}
//#endregion
export { canonicalJson };
//# sourceMappingURL=canonical.mjs.map