Files and data

Catch malformed JSON before using imported data

Wrap JSON.parse in a controlled error boundary when reading external text. Separate syntax failure from later schema validation so a valid JSON value is not automatically treated as usable application data.

Worked example

Node.js example · save as example.mjs and run node example.mjs

function parseImport(text) {
  try { return {ok: true, value: JSON.parse(text)}; }
  catch { return {ok: false, error: "The file is not valid JSON"}; }
}
console.log(parseImport('{"count":3}').value.count);
console.log(parseImport('{"count":}').ok);

How it works

The parser accepts JSON syntax and produces a JavaScript value. The wrapper returns a predictable success or failure shape without exposing an engine-specific error message as the entire user experience. The caller can then validate the successful value.

Limits and mistakes

Valid JSON includes strings, numbers, booleans, and null, not just arrays and objects. Parsing does not prove that required fields exist. Keep the original file unchanged when diagnosing errors rather than trying random text replacements.

Check the result

Expect 3 and false. Add a valid top-level null fixture and confirm the syntax stage accepts it; a separate application validation stage should decide whether it is allowed.

Sources

Reference documentation for the behavior used in this guide: