safe-json-decode
v1.1.0
Published
A minimal package for encoding and decoding json without unhandled exceptions being thrown on failure
Downloads
33
Maintainers
Readme
safe-json-decode
safe-json-decode is a minimal package for encoding and decoding json without unhandled exceptions being thrown on failure
Package is bundled using unbuild
Installation
npm i safe-json-decode
In Node.js
// ESM:
import { safeJsonDecode, safeJsonEncode } from 'safe-json-decode';
// CommonJS:
const { safeJsonDecode, safeJsonEncode } = require('safe-json-decode');Usage
// Same behavior as JSON.parse with valid JSON
safeJsonDecode('{ "foo": "bar" }'); // => {foo: 'bar'}
// Returns null if JSON.parse fails
safeJsonDecode('{ invalid }'); // => null
// Same behavior as JSON.stringify with value that can be serialized
safeJsonEncode({ foo: 'bar' }); // => '{"foo": "bar"}'
// Returns null if JSON.stringify fails
const objectWithCircularReference = {};
objectWithCircularReference.self = objectWithCircularReference;
safeJsonEncode(objectWithCircularReference);
// Handle side effects if error is caught
const handleError = (error) => console.error(error);
safeJsonDecode('{ invalid }', undefined, handleError);
safeJsonEncode(objectWithCircularReference, undefined, undefined, handleError);