safe-json-parse-result
v1.0.2
Published
JSON.parse, but never crashes.
Maintainers
Readme
safe-json-parse-result
A safer alternative to JSON.parse that never throws, returning a result object instead.
Features
- ✅ Never Crashes: Catching invalid JSON errors so your app doesn't have to.
- ✅ Clean API: Returns
{ data, error }object. - ✅ Type Safe: Generic support for returned data types.
- ✅ Default Value: Optionally provide a default value if parsing fails.
- ✅ Dual Support: Works with both ES Modules (ESM) and CommonJS (CJS).
Installation
npm install safe-json-parse-resultUsage
Basic Usage
import { safeJsonParse } from 'safe-json-parse-result';
const json = '{"name": "Poly", "age": 30}';
const { data, error } = safeJsonParse(json);
if (error) {
console.error('Failed to parse JSON:', error);
} else {
console.log(data.name); // Poly
}Handling Invalid JSON
const badJson = '{"name": "Poly", "age": 30'; // Missing closing brace
const { data, error } = safeJsonParse(badJson);
if (error) {
console.log('Caught error:', error.message); // Unexpected end of JSON input...
}With Default Value
const { data } = safeJsonParse(badJson, { name: 'Guest' });
console.log(data.name); // GuestCommonJS (require)
const { safeJsonParse } = require('safe-json-parse-result');
const { data } = safeJsonParse('{}');API
safeJsonParse<T>(json: string, defaultValue?: T): { data: T | null, error: Error | null }
- json: The JSON string to parse.
- defaultValue: (Optional) Value to return in
dataif parsing fails. - Returns: An object containing:
data: The parsed object (or default value, or null).error: The error object if parsing failed, otherwise null.
License
MIT
Author: Ahmer Arain
