How to Validate JSON in JavaScript
There's no need for a library to validate JSON in JavaScript — the language has
it built in. The trick is knowing how to use JSON.parse correctly and how to
read the errors it throws.
The reliable way: JSON.parse in a try/catch
JSON.parse throws a SyntaxError on invalid input, so wrap it:
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
}
If you also want the parsed value (you usually do), return it instead of a boolean:
function tryParseJSON(str) {
try {
return { ok: true, value: JSON.parse(str) };
} catch (err) {
return { ok: false, error: err.message };
}
}
Reading the error
Modern engines point at the problem. A message like
Unexpected token } in JSON at position 42 tells you the character offset — you
can turn that into a line and column by counting newlines up to that index,
which is exactly what a good formatter shows you visually.
Common mistakes
- Single quotes — JSON requires double quotes for keys and strings.
- Trailing commas —
[1, 2, 3,]is invalid JSON (valid JS, invalid JSON). - Unquoted keys —
{ name: "x" }is a JS object literal, not JSON. undefined/ functions / comments — none are allowed in JSON.- Confusing "valid JSON" with "the shape I expect" —
JSON.parseonly checks syntax. Validate the structure separately (or with a schema).
Try it
Paste your JSON to validate and format it — invalid input shows the exact line and column of the problem, so you can fix it fast.