A TypeScript utility for safely serializing objects to JSON, handling circular references gracefully.
Handles Circular References: Automatically replaces circular references with a placeholder string [Circular]. Custom Replacer Function: Allows for custom transformations on values during serialization. Custom Indentation: Supports custom indentation for pretty-printing the JSON string. Installation To install the package, you can use npm or yarn:
npm install @hheimerd/safe-json-stringify
or
yarn add @hheimerd/safe-json-stringify
Import the safeJsonStringify function into your project and use it to serialize objects to JSON:
import {safeJsonStringify} from '@hheimerd/safe-json-stringify';
const obj = {
name: 'John',
circularRef: null,
};
obj.circularRef = obj;
const jsonString = safeJsonStringify(obj);
console.log(jsonString); // {"name":"John","circularRef":"[Circular]"}
const replacer = (key: string, value: unknown) => {
if (value && typeof value === 'object' && Object.getPrototypeOf !== Object.prototype) {
return;
}
return value;
};
const jsonString = safeJsonStringify(obj, replacer);
const replacer = (key: string, value: unknown) => {
if (value === '[Circular]') {
return '[CustomCircular]';
}
return value;
};
const jsonString = safeJsonStringify(obj, replacer);
// lvl 0
const obj = {
// lvl 1
field: {
// lvl 2
value: 'value'
}
}
const replacer = (key: string, value: unknown, depth: number) => {
if (depth > 10) {
return;
}
return value;
};
const jsonString = safeJsonStringify(obj, replacer);
This project is licensed under the MIT License.