An open API service indexing awesome lists of open source software.

https://github.com/vinsjo/safe-json-decode

A minimal package for encoding and decoding JSON-data without thrown errors
https://github.com/vinsjo/safe-json-decode

json

Last synced: 9 months ago
JSON representation

A minimal package for encoding and decoding JSON-data without thrown errors

Awesome Lists containing this project

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](https://www.npmjs.com/package/unbuild)

## Installation

`npm i safe-json-decode`

### In Node.js

```js
// ESM:
import { safeJsonDecode, safeJsonEncode } from 'safe-json-decode';
// CommonJS:
const { safeJsonDecode, safeJsonEncode } = require('safe-json-decode');
```

## Usage

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