JSON.parse in JavaScript: Safe Parsing Guide
JSON.parse() converts a JSON string into a JavaScript value. The main rule: parsing can fail, so production code should treat untrusted JSON as input that must be handled and validated.
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.
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.
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 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.
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.