codeJavaScript

How to Parse JSON in JavaScript

Complete guide to JSON.parse() and JSON.stringify() in JavaScript — with code examples, error handling patterns, and tips for working with APIs.

JSON.parse() — Parsing a JSON String

JSON.parse() converts a JSON string into a JavaScript value (object, array, string, number, boolean, or null). It's built into every JavaScript engine — no import needed.

// Parse a JSON string into a JS object
const jsonString = '{"name":"Alice","age":30,"active":true}';
const user = JSON.parse(jsonString);

console.log(user.name);   // "Alice"
console.log(user.age);    // 30
console.log(user.active); // true

// Parse a JSON array
const jsonArray = '[1, 2, 3, "four"]';
const arr = JSON.parse(jsonArray);
console.log(arr[3]); // "four"

// Parse nested JSON
const nested = '{"user":{"id":1,"roles":["admin","editor"]}}';
const data = JSON.parse(nested);
console.log(data.user.roles[0]); // "admin"

If the input string is not valid JSON, JSON.parse() throws a SyntaxError. Always use validate your JSON before parsing in production code.

Error Handling with try/catch

JSON.parse() throws synchronously when the input is invalid. Always wrap it in a try/catch when parsing user input, API responses, or any untrusted source.

// Safe JSON parse wrapper
function safeParseJSON(jsonString) {
  try {
    return { data: JSON.parse(jsonString), error: null };
  } catch (e) {
    return { data: null, error: e.message };
  }
}

const { data, error } = safeParseJSON('{"name": "Alice"}');
if (error) {
  console.error('Invalid JSON:', error);
} else {
  console.log(data.name); // "Alice"
}

// TypeScript version
function safeParseJSON<T>(jsonString: string): T | null {
  try {
    return JSON.parse(jsonString) as T;
  } catch {
    return null;
  }
}

JSON.stringify() — Serializing to JSON

JSON.stringify() is the inverse of JSON.parse() — it converts a JavaScript value into a JSON string.

const user = { name: "Alice", age: 30, active: true };

// Basic serialization
JSON.stringify(user);
// '{"name":"Alice","age":30,"active":true}'

// Pretty-print with 2-space indentation
JSON.stringify(user, null, 2);
// {
//   "name": "Alice",
//   "age": 30,
//   "active": true
// }

// With a replacer to exclude fields
JSON.stringify(user, ['name', 'age']);
// '{"name":"Alice","age":30}'

// Deep clone via stringify/parse (quick trick)
const clone = JSON.parse(JSON.stringify(user));

Note: JSON.stringify() drops undefined values, functions, and Symbols. Values like NaN and Infinity become null.

Using the Reviver Function

The second argument to JSON.parse() is a reviver function — called for each key/value pair, allowing you to transform values during parsing (e.g., converting date strings into Date objects).

const json = '{"name":"Alice","createdAt":"2024-01-15T10:30:00Z"}';

const user = JSON.parse(json, (key, value) => {
  // Convert ISO date strings to Date objects
  if (key === 'createdAt') return new Date(value);
  return value;
});

console.log(user.createdAt instanceof Date); // true
console.log(user.createdAt.getFullYear());   // 2024

Parsing JSON from fetch() Responses

When using the Fetch API, use response.json() instead of manually calling JSON.parse(). It reads the response body stream and parses it automatically.

// Modern async/await pattern
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  const user = await response.json(); // auto-parses JSON
  return user;
}

// With error handling
async function fetchUserSafe(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (e) {
    console.error('Fetch failed:', e.message);
    return null;
  }
}

Common JSON Parse Errors in JavaScript

SyntaxError: Unexpected token ' in JSON

Cause: Single quotes used instead of double quotes

Fix: Ensure all strings use double quotes. Use JSON.stringify() to serialize — never build JSON strings manually.

SyntaxError: Unexpected token u in JSON at position 0

Cause: JSON.parse(undefined) — the value is undefined, not a string

Fix: Check that the value you're parsing is a non-empty string: if (typeof input === "string") { JSON.parse(input); }

SyntaxError: Unexpected end of JSON input

Cause: Parsing an empty string "" or a truncated response

Fix: Check response.ok before parsing. Check that the string is not empty before calling JSON.parse().

TypeError: Cannot read properties of null

Cause: JSON.parse returned null and you accessed a property on it

Fix: JSON.parse("null") returns the JavaScript value null. Check the result is not null before accessing properties.

Parse JSON in Other Languages

FAQ

How do I parse JSON in JavaScript?expand_more

Use JSON.parse(jsonString) to convert a JSON string into a JavaScript object. Example: const obj = JSON.parse('{"name":"Alice"}'); // obj.name === "Alice"

What is the difference between JSON.parse() and JSON.stringify()?expand_more

JSON.parse() converts a JSON string into a JavaScript object (deserialize). JSON.stringify() converts a JavaScript object into a JSON string (serialize). They are inverse operations.

How do I handle JSON.parse() errors in JavaScript?expand_more

Wrap JSON.parse() in a try/catch block. If the input is not valid JSON, JSON.parse() throws a SyntaxError. Example: try { const data = JSON.parse(input); } catch (e) { console.error("Invalid JSON:", e.message); }

How do I parse JSON from a fetch() API call in JavaScript?expand_more

Use response.json() which automatically parses the response body as JSON. Example: const response = await fetch(url); const data = await response.json(); No need to call JSON.parse() manually.

How to Parse JSON in JavaScript