Safe JSON Parse With Result Type
Parse untrusted JSON without exceptions by returning a discriminated Result, with an optional type-predicate validation layer.
Code
export type Result<Value, Failure> =
| { readonly ok: true; readonly value: Value }
| { readonly ok: false; readonly error: Failure };
export type JsonParseError =
| { readonly reason: "syntax"; readonly message: string }
| { readonly reason: "validation"; readonly message: string };
export function parseJson<Value = unknown>(text: string): Result<Value, JsonParseError> {
if (typeof text !== "string") throw new TypeError("text must be a string");
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch (error) {
return {
ok: false,
error: { reason: "syntax", message: error instanceof Error ? error.message : String(error) },
};
}
return { ok: true, value: parsed as Value };
}
export function parseJsonWith<Value>(
text: string,
guard: (value: unknown) => value is Value,
): Result<Value, JsonParseError> {
if (typeof guard !== "function") throw new TypeError("guard must be a type predicate function");
const result = parseJson<unknown>(text);
if (!result.ok) return result;
if (!guard(result.value)) {
return {
ok: false,
error: { reason: "validation", message: "value did not match the expected shape" },
};
}
return { ok: true, value: result.value };
}
interface User {
readonly id: string;
readonly name: string;
}
function isUser(value: unknown): value is User {
if (value === null || typeof value !== "object") return false;
const record = value as Record<string, unknown>;
return typeof record.id === "string" && typeof record.name === "string";
}
const valid = parseJsonWith('{"id":"u1","name":"Ada"}', isUser);
if (valid.ok) console.log(valid.value.name);
else console.log(valid.error.reason);
const invalid = parseJsonWith("{oops}", isUser);
console.log(invalid);
const wrongShape = parseJsonWith('{"id":1}', isUser);
console.log(wrongShape);Output
Captured from a sandboxed run of this snippet in the build pipeline.
Ada
{
ok: false,
error: {
reason: 'syntax',
message: "Expected property name or '}' in JSON at position 1 (line 1 column 2)"
}
}
{
ok: false,
error: {
reason: 'validation',
message: 'value did not match the expected shape'
}
}How it works
Count the functions parseJson, parseJsonWith and isUser as the entire surface area of Safe JSON Parse With Result Type.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
The result comes back as an object carrying true.
What to watch for
- The guard
typeof text !== "string"short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
Import parseJson from the file and call it — the rest of the code is implementation detail.
The call returns true.
Core lines
if (typeof guard !== "function") throw new TypeError("guard must be a type predicate function");
if (typeof text !== "string") throw new TypeError("text must be a string");
return typeof record.id === "string" && typeof record.name === "string";
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
FAQ
- Does `parseJson` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- How are precondition violations signaled?
- It throws `TypeError` before any real work runs, via the guard `typeof text !== "string"` — handle it at the call site or let it propagate deliberately.
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `parseJson`, `parseJsonWith`, `isUser` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.