JSON.parse() in JavaScript — complete guide with examples
Everything about JSON.parse(): syntax, the reviver parameter, error handling, and safe parsing patterns for fetch responses and localStorage.
JSON.parse() converts a JSON string into a JavaScript value. It is the standard way to deserialize data you receive from an API, read from localStorage, or load from a file.
Basic syntax
JSON.parse(text) JSON.parse(text, reviver)
The first argument is the string to parse. The optional second argument is a reviver function that transforms values as they are reconstructed.
Simple examples
// Parse a JSON object
const user = JSON.parse('{"name":"Ada","age":30}');
console.log(user.name); // "Ada"
// Parse a JSON array
const ids = JSON.parse('[1, 2, 3]');
console.log(ids[0]); // 1
// Parse a primitive
const n = JSON.parse('42'); // number 42
const b = JSON.parse('true'); // boolean true
const z = JSON.parse('null'); // nullParsing fetch responses
The fetch API returns a Response object. Use response.json() instead of manually calling JSON.parse — it handles streaming and charset detection automatically.
// Preferred: response.json() for fetch
const res = await fetch('/api/users');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const users = await res.json();
// Manual (only needed for edge cases)
const text = await res.text();
const data = JSON.parse(text);Safe parsing — wrapping in try/catch
JSON.parse throws a SyntaxError for any malformed input. Always wrap it in try/catch when the input comes from outside your control.
function safeParse(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch (err) {
return { ok: false, error: err.message };
}
}
const result = safeParse(apiResponse);
if (!result.ok) {
console.error('Bad JSON:', result.error);
} else {
console.log(result.value);
}The reviver parameter
The reviver function receives each key-value pair bottom-up and returns the value to use. Return undefined to delete the property.
// Convert ISO date strings to Date objects
const data = JSON.parse(json, (key, value) => {
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
return new Date(value);
}
return value;
});
// Remove null values
const clean = JSON.parse(json, (key, value) =>
value === null ? undefined : value
);Parsing localStorage values
// Write
localStorage.setItem('prefs', JSON.stringify({ theme: 'dark', fontSize: 14 }));
// Read safely
function getPrefs() {
try {
const raw = localStorage.getItem('prefs');
return raw ? JSON.parse(raw) : null;
} catch {
return null;
}
}Common errors
- SyntaxError: Unexpected token — the string is not valid JSON. Common causes: trailing comma, single quotes, or the server returned an HTML error page.
- SyntaxError: Unexpected end of JSON input — the string is empty or was truncated. Check that your response body is complete.
- SyntaxError: Unexpected token < in JSON at position 0 — the server returned an HTML page (usually a 404 or 500 error) instead of JSON. Check res.ok before parsing.
Paste your JSON into the validator →
Get the exact line, column, and a fix hint in seconds — no upload, no signup.
Open JSON Validator →