Skip to content

Like JSON stringify/parse, but never throws on circular references and BigInt values

License

Notifications You must be signed in to change notification settings

icmx/calmer-json

Repository files navigation

calmer-json

Like JSON stringify/parse, but never throws on circular references and BigInt values.

Usage

npm install calmer-json

toJson — stringify

const text = toJson(value, options?)
  • value Value to stringify to a JSON text
  • options.replacer? Function to transform value entries (if any)
  • options.space? String to use to ident or number of spaces for identation
  • options.onError? Callback to handle possible errors and provide a fallback value

Unlike JSON.stringify, toJson never throws on circular references or BigInt values. It just ignores them as non-serializable:

const example = {
  circular: null,
  bigint: BigInt('1'),
  foo: 'bar',
};

example.circular = example;

toJson(example); // -> '{"foo":"bar"}'

fromJson — parse

const value = fromJson(text, options?)
  • text String to parse from JSON text to a value
  • options.reviver? Function to transform value entries (if any)
  • options.onError? Callback to handle possible errors and provide a fallback value