Skip to main content

Function: safeJsonParse()

safeJsonParse<T>(json: string, validator: (data: unknown) => data is T): SafeJsonResult<T>

Defined in: shared/utils/jsonSafety.ts:105

Safely parse JSON string with type validation.

Type Parametersโ€‹

Tโ€‹

T

Parametersโ€‹

jsonโ€‹

string

JSON string to parse

validatorโ€‹

(data: unknown) => data is T

Type guard function to validate the parsed data

Returnsโ€‹

SafeJsonResult<T>

Safe result object with parsed data or error

Exampleโ€‹

const result = safeJsonParse(jsonString, (data): data is User => {
return (
typeof data === "object" &&
data !== null &&
typeof data.id === "string" &&
typeof data.name === "string"
);
});

if (result.success) {
console.log(result.data.name); // Type-safe access
} else {
console.error(result.error);
}

Throwsโ€‹

Never throws - all errors are captured and returned in the result object