JSON.parse in JavaScript: Safe Parsing Guide
Last updated:
JSON.parse() converts a JSON string into the corresponding JavaScript value — object, array, string, number, boolean, or null — throwing a SyntaxError on any malformed input. The 5 most common triggers are single-quoted strings, unquoted keys, trailing commas, JavaScript comments, and the literals undefined or NaN. The optional 2nd argument is a reviver function for transforming values after parsing, typically to convert ISO 8601 date strings into Date objects, available in all ES2020+ environments. This guide covers safe parsing with try/catch, the reviver API, TypeScript's unknown cast, a safe-parse wrapper returning null on error, and shape validation with Zod.
The optional second argument is a reviver function that runs after parsing and lets you transform values — for example, converting ISO date strings into real Date objects — before the final value is returned. This page covers safe parsing patterns, error handling, the reviver API, and validation strategies for production use.
Basic JSON.parse usage
Pass a valid JSON string to JSON.parse(). The result is a JavaScript object, array, string, number, boolean, or null.
const raw = '{"id":42,"name":"Alice","active":true}'
const user = JSON.parse(raw)
console.log(user.name)
// AliceJSON is stricter than JavaScript object literals. Keys and string values must use double quotes, and trailing commas are not allowed.
If you need the reverse workflow, convert values back with JavaScript object to JSON.
Always catch parse errors for untrusted input
Invalid JSON throws a SyntaxError. Use try/catch when parsing user input, localStorage values, uploaded files, or external API responses.
function safeJsonParse(raw) {
try {
return { ok: true, value: JSON.parse(raw) }
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : 'Invalid JSON'
}
}
}Common JSON.parse errors
- Single quotes:
{'name':'Alice'}is JavaScript-like, but not valid JSON. - Unquoted keys:
{name:"Alice"}is not valid JSON. - Trailing commas:
{"name":"Alice",}is invalid. - Comments:
// commentand/* comment */are not allowed. - Literal newlines inside strings must be escaped as
\n.
For concrete broken-input examples and fixes, see JSON.parse error in JavaScript.
Use a reviver to transform parsed values
The second argument is a reviver function. It runs after parsing and lets you transform values before the final object is returned.
const raw = '{"name":"Alice","createdAt":"2024-01-15T10:30:00.000Z"}'
const user = JSON.parse(raw, (key, value) => {
if (key.endsWith('At') && typeof value === 'string') {
return new Date(value)
}
return value
})
console.log(user.createdAt instanceof Date)
// trueKeep revivers predictable. They are useful for dates and numeric strings, but broad transforms can make parsing harder to reason about.
Parsing nested JSON
Many payloads contain deep objects and arrays. After parsing, use optional chaining and array guards when accessing nested values so missing branches do not crash your code.
The full walkthrough is in parse nested JSON in JavaScript.
Parsing JSON from fetch
response.json() already parses JSON internally. It still throws if the body is not valid JSON, and it does not guarantee the shape of the result.
const response = await fetch('/api/user')
if (!response.ok) {
throw new Error('Request failed')
}
const data = await response.json()
if (!data || typeof data !== 'object' || !('id' in data)) {
throw new Error('Unexpected response shape')
}Parsing JSON from localStorage
Values in localStorage are strings or null. Always handle missing values and stale data from older app versions.
function readSettings() {
const raw = localStorage.getItem('settings')
if (raw === null) return { theme: 'light' }
try {
return JSON.parse(raw)
} catch {
localStorage.removeItem('settings')
return { theme: 'light' }
}
}Parsing is not validation
JSON.parse() only checks syntax. It does not prove that an object has the fields your app needs.
const data = JSON.parse('{"email":123}')
// This parsed successfully, but email is the wrong type.
if (typeof data.email !== 'string') {
throw new Error('email must be a string')
}For larger payloads, use JSON Schema or runtime validation after parsing.
If you want copy-paste validation snippets, see JSON Schema examples.
Validate JSON before parsing
Paste JSON into Jsonic's JSON Formatter & Validator to find syntax errors, or use the JSON Schema Validator to check object shape.
Frequently asked questions
What does JSON.parse return for different input types?
It returns a matching JavaScript value: an object for a JSON object string, an array for a JSON array, a string for a quoted string, a number, a boolean, or null. It never returns undefined. Invalid input throws a SyntaxError.
How do I handle JSON.parse errors?
Wrap the call in try/catch. JSON.parse throws SyntaxError for any invalid JSON. Return a safe fallback or rethrow with a descriptive message that includes the raw input for debugging.
What is a reviver function in JSON.parse?
The second argument is a reviver called for every parsed key-value pair. Return a new value to transform it, or return undefined to remove the property. Commonly used to convert ISO date strings back into Date objects.
Can JSON.parse parse arrays?
Yes. Any valid JSON value is accepted at the top level, including arrays.JSON.parse('[1,2,3]') returns the JavaScript array [1, 2, 3].
What inputs throw SyntaxError in JSON.parse?
Single quotes, trailing commas, unquoted keys, comments, undefined,NaN, Infinity, and literal newlines inside strings all cause a SyntaxError.
How do I safely parse JSON in production?
Use try/catch, then validate the parsed result shape before consuming it. Check required fields and their types. For complex payloads, use a JSON Schema validator or a library like Zod.
Further reading and primary sources
- ECMA-262 — JSON.parse — The official ECMAScript spec defining JSON.parse semantics
- MDN — JSON.parse() — Reviver syntax, errors, and browser support
- RFC 8259 — The JavaScript Object Notation (JSON) Data Interchange Format — Authoritative JSON grammar that JSON.parse follows
- Zod — TypeScript-first schema validation — Recommended runtime validator for untrusted JSON
Recommended reading
- Effective TypeScript (2nd Edition) — Dan Vanderkam83 concrete ways to level up your TypeScript — inference, narrowing, and type-safe API boundaries.
- JavaScript: The Definitive Guide (7th Edition) — David FlanaganThe complete reference for the language JSON came from — serialization, async, and the full standard library.
As an Amazon Associate, Jsonic earns from qualifying purchases.