To validate whether a string is valid JSON in JavaScript, wrap JSON.parse(input) inside a try / catch block after verifying typeof input === "string"—and when you also need structural/type guarantees (for example, requiring a JSON object rather than a top-level string, number, boolean, null, or array), inspect the parsed value explicitly after JSON.parse() succeeds. Avoid using regular expressions or eval()/new Function() to validate JSON, as regexes cannot reliably enforce nested grammar rules and dynamic code evaluation introduces severe security risks.
1. Validating JSON Syntax with typeof and try / catch Around JSON.parse()
JSON.parse() throws a SyntaxError on malformed JSON, unquoted keys, trailing commas, single-quoted strings, or undefined—validate the input type first and return a structured result or boolean cleanly:
// Validate whether a string parses as valid JSON without throwing
function validateJsonString(rawText, { requireObject = false, allowArrayRoot = true } = {}) {
if (typeof rawText !== "string") {
throw new TypeError("Expected rawText to be a string.");
}
if (typeof requireObject !== "boolean" || typeof allowArrayRoot !== "boolean") {
throw new TypeError("Expected requireObject and allowArrayRoot to be booleans.");
}
const trimmed = rawText.trim();
if (trimmed.length === 0) {
return { isValid: false, data: null, error: "Input string is empty or whitespace-only." };
}
try {
const parsed = JSON.parse(trimmed);
if (requireObject) {
const isPlainObject = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed);
const isAllowedArray = allowArrayRoot && Array.isArray(parsed);
if (!isPlainObject && !isAllowedArray) {
return {
isValid: false,
data: null,
error: allowArrayRoot
? "Parsed JSON must be a non-null object or array."
: "Parsed JSON must be a non-null plain object."
};
}
}
return { isValid: true, data: parsed, error: null };
} catch (error) {
return {
isValid: false,
data: null,
error: error instanceof Error ? error.message : String(error)
};
}
}
// Example usage:
try {
console.log(validateJsonString('{"ok":true,"count":3}')); // { isValid: true, data: { ok: true, count: 3 }, error: null }
console.log(validateJsonString("{bad: 'json'}")); // { isValid: false, data: null, error: "..." }
console.log(validateJsonString('"just a string"', { requireObject: true })); // { isValid: false, ... }
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
JSON.parse('"hello"')orJSON.parse('123')is syntactically valid JSON: Check the parsed value’s type if your endpoint or config expects an object () or array ([...]).- Reject empty strings explicitly:
JSON.parse("")throws aSyntaxError, and checkingtrimmed.length === 0gives clear diagnostic context immediately.
2. Enforcing Schema / Required Keys After JSON.parse()
Syntactically valid JSON ("{}") can still be semantically invalid for your application if required keys, types, or bounds are missing—pair JSON.parse() with explicit field checks using Map or Object.hasOwn():
// Parse JSON and verify required fields and types for a structured payload
function parseJsonWithSchema(rawText, requiredTypesMap) {
if (typeof rawText !== "string") {
throw new TypeError("Expected rawText to be a string.");
}
if (!(requiredTypesMap instanceof Map)) {
throw new TypeError("Expected requiredTypesMap to be a Map of fieldName -> expectedType.");
}
let parsed;
try {
parsed = JSON.parse(rawText);
} catch (error) {
throw new SyntaxError(`Invalid JSON syntax: ${error.message}`);
}
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new TypeError("Expected root JSON value to be a plain object.");
}
for (const [field, expectedType] of requiredTypesMap.entries()) {
if (!Object.hasOwn(parsed, field)) {
throw new TypeError(`Missing required JSON field "${field}".`);
}
const value = parsed[field];
const actualType = Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
if (actualType !== expectedType) {
throw new TypeError(`Expected field "${field}" to have type "${expectedType}", got "${actualType}".`);
}
}
return parsed;
}
// Example usage:
try {
const schema = new Map([
["id", "number"],
["enabled", "boolean"],
["tags", "array"]
]);
const record = parseJsonWithSchema('{"id":42,"enabled":true,"tags":["v1"]}', schema);
console.log("Validated record:", record);
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
- Use
Object.hasOwn(parsed, )rather thanparsed[field] !== undefined: Distinguishes missing keys from keys whose value isundefinedornull, and ignores prototype keys. - Avoid mutating untrusted parsed objects before validation: Validate types and copy/project only expected properties.
3. Common JSON Pitfalls in JavaScript
Watch out for inputs that look like JSON or JavaScript object literals but are not valid JSON:
- Trailing commas, single quotes, and comments:
{"a": 1,},{'a': 1}, and// commentare invalid in strict JSON and throwSyntaxErrorinJSON.parse(). NaN,Infinity, and-Infinityare not valid JSON values: Even thoughJSON.stringify({ n: NaN })outputs{"n":null},NaNinside raw JSON text failsJSON.parse().- Watch out for
response.json()vs.response.text()in HTTP clients: When debugging malformed API bodies, reading.text()first lets you inspect or log the exact invalid string before calling your validator.
