The input JSON string to parse.
Optional
validate: (obj: unknown) => obj is TAn optional type guard function to validate the parsed object.
An object containing:
success
: Indicates whether parsing (and validation) succeeded.value
: The parsed object if successful; otherwise null
.error
: An error object if parsing failed or validation was unsuccessful.This utility is useful when working with dynamic or untrusted JSON data,
such as user input, localStorage values, or external API responses.
It prevents runtime exceptions by catching JSON.parse
errors,
and it provides optional runtime validation for extra safety.
Using a type guard function enables strong typing of the return value if validation succeeds.
// ES Module
import { sanitizeJson } from '@bnidev/js-utils'
// CommonJS
const { sanitizeJson } = require('@bnidev/js-utils')
type Person = { name: string }
function isPerson(obj: unknown): obj is Person {
return typeof obj === 'object' && obj !== null && 'name' in obj && typeof (obj as any).name === 'string'
}
const result = sanitizeJson<Person>('{"name": "Alice"}', isPerson)
if (result.success) {
console.log(result.value.name) // 'Alice'
} else {
console.error(result.error)
}
Safely parses a JSON string and optionally validates the resulting object.