Skip to content

hheimerd/safe-json-stringify

Repository files navigation

npm version

Safe JSON Stringify

A TypeScript utility for safely serializing objects to JSON, handling circular references gracefully.

Features

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

Usage

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]"}

Cook book

Do not serialize classes

const replacer = (key: string, value: unknown) => {
    if (value && typeof value === 'object' && Object.getPrototypeOf !== Object.prototype) {
        return;
    }
    return value;
};

const jsonString = safeJsonStringify(obj, replacer);

Custom circular value

const replacer = (key: string, value: unknown) => {
    if (value === '[Circular]') {
        return '[CustomCircular]';
    }
    return value;
};

const jsonString = safeJsonStringify(obj, replacer);

Max depth

// 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);

License

This project is licensed under the MIT License.

About

JSON.stringify with circular reference resolver

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published