{}JSON FYI

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.

·7 min read

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'); // null

Parsing 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 →

Frequently asked questions

Does JSON.parse mutate the original string?+

No. JSON.parse always creates a new JavaScript value. Strings are immutable in JavaScript, so the input cannot be modified.

Can JSON.parse parse a JSON array at the top level?+

Yes. JSON.parse('[1,2,3]') returns the JavaScript array [1, 2, 3]. Any valid JSON value — object, array, string, number, boolean, or null — is a valid input.

What is the difference between JSON.parse and eval for parsing JSON?+

Never use eval. JSON.parse is safe and spec-compliant. eval executes arbitrary JavaScript, which is a severe security risk when the source is untrusted. JSON.parse only accepts JSON syntax, not JS expressions.

How do I parse JSON with comments?+

You can't — JSON.parse does not support comments. Strip comments first (e.g. strip-json-comments npm package) or switch to JSONC or JSON5 if your tooling supports them.

Related tools & guides