Course contentsShow
← JavaScript
Lesson 680 of 2,72316. Object Methods and PatternsFree lesson

JSON.parse Basics

Parsing JSON strings back into JavaScript values and handling the SyntaxError on invalid JSON.

JSON.parse Basics

You'll learn how to convert JSON strings back into JavaScript values and handle parsing errors safely.

What is JSON.parse?

While JSON.stringify turns JavaScript values into JSON strings, JSON.parse does the reverse—it takes a JSON string and converts it back into a JavaScript object, array, or primitive value. Think of it like unwrapping a package: the JSON string is the sealed box, and JSON.parse opens it to reveal the contents inside.

Basic Usage

const jsonString = '{"name":"Alice","age":30}';
const person = JSON.parse(jsonString);

console.log(person.name); // "Alice"
console.log(person.age); // 30

You can parse arrays too:

const arrayString = '[1, 2, 3]';
const numbers = JSON.parse(arrayString);
console.log(numbers[0]); // 1

Handling Invalid JSON

If the string isn't valid JSON, JSON.parse throws a SyntaxError:

try {
  const result = JSON.parse('{invalid json}');
} catch (error) {
  console.log('Failed to parse:', error.message);
  // "Failed to parse: Unexpected token i in JSON at position 1"
}

Always wrap JSON.parse in a try-catch block when parsing untrusted input, like data from APIs or user uploads.

Common Mistakes

// Single quotes won't work - JSON requires double quotes
JSON.parse("{'name':'Bob'}"); // SyntaxError

// Trailing commas are invalid
JSON.parse('{"name":"Bob",}'); // SyntaxError

Key Takeaway: JSON.parse converts JSON strings back into JavaScript values, but throws a SyntaxError if the string is invalid—always use try-catch for untrusted input.