There is no JSON.isValid() in JavaScript, and none in Python either. The parser is the validator: if JSON.parse succeeds, the text is valid JSON, and if it throws, the error message says why. The interesting part is everything around that: what "valid" should mean for your input, how to report where the problem is, and the edge cases that slip through.
The basic check in JavaScript
Wrap JSON.parse in try/catch and return a boolean:
function isValidJson(text) {
if (typeof text !== "string") return false;
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
isValidJson('{"name":"Ada"}'); // true
isValidJson("{name: 'Ada'}"); // false
The typeof check matters. JSON.parse converts its argument to a string first, so JSON.parse(null) parses the text "null" and succeeds, and JSON.parse(123) returns 123. Without the type check, a missing value can look like valid input.
In most code you want the parsed value too, not just a yes or no. Return both so the input is only parsed once:
function parseJson(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (error) {
return { ok: false, error: error.message };
}
}
Valid JSON isn't always the JSON you expected
JSON allows any value at the top level, so all of these are valid documents:
JSON.parse("42"); // 42
JSON.parse('"hello"'); // "hello"
JSON.parse("null"); // null
JSON.parse("[]"); // []
If your code expects an object, check the shape after parsing:
function parseJsonObject(text) {
const value = JSON.parse(text);
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new TypeError("Expected a JSON object");
}
return value;
}
For anything beyond "is it an object", such as required fields and types, use a schema. The guide to JSON Schema validation with Ajv shows how.
Report where the error is
A message like "Unexpected token" without a position makes a long document hard to fix. Current versions of Chrome, Edge and Node.js (V8) include both the character position and the line and column:
Expected ',' or '}' after property value in JSON at position 20 (line 3 column 3)
Firefox and Safari word their messages differently, and older engines only give a position. If you show errors to users, convert a position to a line and column yourself so the format is the same in every browser:
function lineAndColumn(text, position) {
const before = text.slice(0, position);
const line = before.split("\n").length;
const column = position - before.lastIndexOf("\n");
return { line, column };
}
Extract the position with a regular expression such as /position (\d+)/. If the message doesn't contain one, show the message as it is.
Validate JSON in Python
Python raises json.JSONDecodeError, a subclass of ValueError that already carries the line and column:
import json
def parse_json(text: str):
try:
return json.loads(text), None
except json.JSONDecodeError as error:
return None, f"{error.msg} at line {error.lineno}, column {error.colno}"
parse_json('{"name": "Ada",}')
# (None, "Illegal trailing comma before end of object at line 1, column 15")
# Python 3.12 and earlier: "Expecting property name enclosed in double quotes at line 1, column 16"
One Python-specific difference: by default json.loads accepts NaN, Infinity and -Infinity, which strict JSON does not allow. If the data will be read by other languages, reject them:
def reject_constant(name):
raise ValueError(f"{name} is not valid JSON")
json.loads(text, parse_constant=reject_constant)
Validate JSON from the command line
Both of these exit with a non-zero status for invalid input, which makes them easy to use in CI scripts or Git hooks:
jq empty config.json && echo "valid"
python3 -m json.tool config.json > /dev/null && echo "valid"
jq empty parses the input and prints nothing, so only errors are shown.
The errors you will see most often
| Input | Problem |
|---|---|
{"a": 1,} |
Trailing comma. JSON doesn't allow one before } or ]. |
{'a': 1} |
Single quotes. Strings and keys need double quotes. |
{a: 1} |
Unquoted key, which is JavaScript object syntax but not JSON. |
{"a": 1} // note |
Comments aren't part of JSON. |
{"text": "line one + a real line break |
Raw line breaks inside strings must be escaped as \n. |
| empty string | Usually an empty response body; see the 204 and empty-body cases below. |
Each of these has a dedicated walkthrough: Unexpected token in JSON, Unexpected end of JSON input and Expected double-quoted property name.
Edge cases worth deciding on
- Empty input.
JSON.parse("")throws. If an empty string means "no data" in your app, such as an empty HTTP body from a204 No Content, handle it before parsing. - Duplicate keys.
{"a": 1, "a": 2}parses as{ a: 2 }without any error. Detecting duplicates needs a parser that reports them, such as theyamlpackage's JSON mode or a dedicated JSON linter. - Byte order mark. Files saved by some Windows editors start with a BOM (
\uFEFF), whichJSON.parserejects. Strip it withtext.replace(/^\uFEFF/, "")when reading files. - Big numbers. Integers above 2^53 parse without an error but lose precision. Validity and accuracy are different questions.
Validating JSON from an API
A failed response.json() often isn't a JSON problem at all: the server returned an HTML error page or an empty body. Check the response before parsing:
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const type = response.headers.get("content-type") ?? "";
if (!type.includes("application/json")) throw new Error(`Expected JSON, got ${type}`);
const data = await response.json();
Once the text parses, the next question is whether it has the shape your code expects. In TypeScript, that's where runtime validation of API responses comes in.