@stryke/json
Version:
A package containing JSON parsing/stringify utilities used by Storm Software.
68 lines (66 loc) • 1.52 kB
JavaScript
import { isNumber } from "@stryke/type-checks/is-number";
import { isUndefined } from "@stryke/type-checks/is-undefined";
//#region src/utils/stringify.ts
const invalidKeyChars = [
"@",
"/",
"#",
"$",
" ",
":",
";",
",",
".",
"!",
"?",
"&",
"=",
"+",
"-",
"*",
"%",
"^",
"~",
"|",
"\\",
"\"",
"'",
"`",
"{",
"}",
"[",
"]",
"(",
")",
"<",
">"
];
/**
* Stringify a value to a JSON-like string.
*
* @param value - The value to stringify
* @param spacing - The spacing to use for the stringification
* @returns The stringified value
*/
const stringify = (value, spacing = 2) => {
const space = isNumber(spacing) ? " ".repeat(spacing) : spacing;
switch (value) {
case null: return "null";
case void 0: return "\"undefined\"";
case true: return "true";
case false: return "false";
case Number.POSITIVE_INFINITY: return "infinity";
case Number.NEGATIVE_INFINITY: return "-infinity";
}
if (Array.isArray(value)) return `[${space}${value.map((v) => stringify(v, space)).join(`,${space}`)}${space}]`;
if (value instanceof Uint8Array) return value.toString();
switch (typeof value) {
case "number": return `${value}`;
case "string": return JSON.stringify(value);
case "object": return `{${space}${Object.keys(value).filter((key) => !isUndefined(value[key])).map((key) => `"${key}": ${space}${stringify(value[key], space)}`).join(`,${space}`)}${space}}`;
default: return "null";
}
};
//#endregion
export { invalidKeyChars, stringify };
//# sourceMappingURL=stringify.mjs.map