-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathstringifyJson.ts
More file actions
33 lines (26 loc) · 924 Bytes
/
stringifyJson.ts
File metadata and controls
33 lines (26 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { isObject } from "../lang";
/**
* Recursively sorts object keys and stringifies a value to ensure a deterministic output.
* This is crucial for consistent hashing of objects.
*
* @param {unknown} value - The value to stringify.
* @returns {string} A stable JSON string representation of the value.
* @see {@link parseJson}
* @since 1.0.0
* @version 1.0.0
*/
export function stringifyJson(value: unknown): string {
if (!isObject(value)) {
return JSON.stringify(value);
}
if (Array.isArray(value)) {
return `[${value.map((element) => stringifyJson(element)).join(",")}]`;
}
const keys = Object.keys(value).sort();
const pairs = keys.map((key) => {
const stringifiedKey = JSON.stringify(key);
const stringifiedValue = stringifyJson((value as Record<string, unknown>)[key]);
return `${stringifiedKey}:${stringifiedValue}`;
});
return `{${pairs.join(",")}}`;
}