@stryke/json
Version:
A package containing JSON parsing/stringify utilities used by Storm Software.
69 lines (67 loc) • 1.71 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
let _stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
let _stryke_type_checks_is_undefined = require("@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 = (0, _stryke_type_checks_is_number.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) => !(0, _stryke_type_checks_is_undefined.isUndefined)(value[key])).map((key) => `"${key}": ${space}${stringify(value[key], space)}`).join(`,${space}`)}${space}}`;
default: return "null";
}
};
//#endregion
exports.invalidKeyChars = invalidKeyChars;
exports.stringify = stringify;