@spa-tools/utilities
jsonStringify()
The JSON.stringify()
method is a great way to encode JavaScript objects into
strings; however, it fails if the object contains a circular reference or a
BigInt
value.
The jsonStringify()
method is a friendly replacement that gracefully handles these cases.
Usage
import { jsonStringify } from '@spa-tools/utilities';
const objWithBigInt = {
a: 1,
b: '2',
c: BigInt(12345678901234567890n),
d: {
e: 4,
f: '5',
},
};
console.log(jsonStringify(objWithBigInt));
// --> {"a":1,"b":"2","c":"12345678901234567890","d":{"e":4,"f":"5"}}
const objWithCircularRef = {
a: 1,
b: '2',
};
objWithCircularRef.c = objWithCircularRef;
console.log(jsonStringify(objWithCircularRef));
// --> {"a":1,"b":"2","c":"[Circular Reference]"}
Arguments
Name | Type | Required? | Default | Description |
---|---|---|---|---|
obj | unknown | yes | - | The object to stringify |
space | string | number | no | '' | A string or number that's used to insert white space (including indentation, line break characters, etc.) into the output JSON string for readability purposes. |
circRefSub | string | no | '[Circular Reference]' | The string to substitute all found circular references with. |
Returns
string
: The JSON string representation of the object.