A valid JSON string to parse. Can contain any valid JSON data type: primitives (string, number, boolean, null), arrays, or objects.
Optional
reviver: (this: unknown, key: string, value: JsonValue) => unknownOptional function that transforms parsed values. Called for each key-value pair in the JSON. The function receives the key name and parsed value, and should return the transformed value. For nested objects, inner objects are processed before outer objects.
A Result<JsonValue, string>
containing:
Result.ok(parsedValue)
where parsedValue
is the parsed JSONResult.err(errorMessage)
where errorMessage
describes the
parsing errorconst validJson = '{"name": "Alice", "age": 30}';
const invalidJson = '{invalid json}';
const parsed = Json.parse(validJson);
const failed = Json.parse(invalidJson);
assert.ok(Result.isOk(parsed));
if (Result.isOk(parsed)) {
assert.deepStrictEqual(parsed.value, { name: 'Alice', age: 30 });
}
assert.ok(Result.isErr(failed));
// With reviver
const jsonWithDate = '{"created": "2024-01-01T00:00:00.000Z"}';
const withReviver = Json.parse(jsonWithDate, (key, value) => {
if (key === 'created' && typeof value === 'string') {
return new Date(value);
}
return value;
});
assert.ok(Result.isOk(withReviver));
Safely converts a JSON string into a JavaScript value without throwing exceptions.
This function provides type-safe JSON parsing by wrapping the native
JSON.parse
in aResult
type, allowing you to handle parsing errors gracefully without try-catch blocks.