datasquirel/package-shared/utils/ejson.ts

39 lines
829 B
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
/**
* # EJSON parse string
*/
function parse(
string: string | null | number,
reviver?: (this: any, key: string, value: any) => any
): { [s: string]: any } | { [s: string]: any }[] | undefined {
if (!string) return undefined;
if (typeof string == "object") return string;
if (typeof string !== "string") return undefined;
try {
return JSON.parse(string, reviver);
} catch (error) {
return undefined;
}
}
/**
* # EJSON stringify object
*/
function stringify(
value: any,
replacer?: (this: any, key: string, value: any) => any,
space?: string | number
): string | undefined {
try {
return JSON.stringify(value, replacer, space);
} catch (error) {
return undefined;
}
}
const EJSON = {
parse,
stringify,
};
export default EJSON;