parseJSON
Parses an unknown value into a valid JSON value. This parser combines the normalizeJSON semantic normalizer with the validateJSON structural validator to produce a canonical JSONValue.
The parser never throws and never mutates input. It distinguishes between validation errors (the value is not JSON at all) and normalization errors (the value is JSON‑like but fails normalization rules).
Signature
function parseJSON(
value: unknown,
field?: string,
options?: { strict?: boolean }
): ParseResult<JSONValue>
Behavior
- A value is accepted when:
normalizeJSONreturns a non‑null value.validateJSONconfirms the normalized value is structurally valid JSON.- Examples:
- Objects and arrays in non‑strict mode
- JSON strings that JSON.parse can interpret
- Strict JSON strings with no leading/trailing whitespace
ValidationError:- Returned when the input is not JSON at all.
- Examples:
- Functions.
- Symbols.
- Circular references.
- Objects with non‑plain prototypes.
undefined.- Objects containing non‑JSON values.
- These produce: "Value must be valid JSON"
Returns
A ParseResult
Examples
parseJSON({ a: 1, b: true })
// { ok: true, value: { a: 1, b: true }, issues: [] }
parseJSON(' { "x": 1 } ')
// { ok: true, value: { x: 1 }, issues: [] }
parseJSON('{"x":1}', 'data', { strict: true })
// { ok: true, value: { x: 1 }, issues: [] }
parseJSON(' { "x": 1 } ', 'data', { strict: true })
// { ok: false, value: null, issues: ["Value could not be normalized into valid JSON"] }
parseJSON(() => {}, 'payload')
// { ok: false, value: null, issues: ["Value must be valid JSON"] }
Notes
- The parser distinguishes structural JSON correctness from normalization rules.
- Strict mode is ideal for configuration files or security‑sensitive contexts.
- Non‑strict mode is more permissive and accepts already‑parsed objects and arrays.
- The parser never mutates input and never throws.