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
- Host: GitHub
- URL: https://github.com/vinsjo/safe-json-decode
- Owner: vinsjo
- License: mit
- Created: 2022-08-19T12:33:27.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2025-07-14T09:52:06.000Z (12 months ago)
- Last Synced: 2025-09-21T23:03:58.503Z (10 months ago)
- Topics: json
- Language: TypeScript
- Homepage:
- Size: 626 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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);
```