Lesson 6 — Working with JSON

Parsing JSON in JavaScript

Parsing converts a JSON text string into a native JavaScript object or array that your code can actually work with — read properties from, loop over, and modify.

JSON.parse()

JSON.parse() takes a JSON-formatted string and returns the equivalent JavaScript value — usually an object or an array, ready to be used directly in your code.

JavaScript — Parsing JSON
const jsonText = '{"name": "Tumi", "age": 30}';
const data = JSON.parse(jsonText);

console.log(data.name); // Tumi
console.log(data.age);  // 30

Handling Parsing Errors

If the input isn't valid JSON, JSON.parse() throws an error. Wrapping it in a try/catch prevents malformed data — for example, from an unreliable API — from crashing your entire script.

JavaScript — Safe parsing
try {
    const data = JSON.parse(jsonText);
    console.log(data);
} catch (error) {
    console.error("Invalid JSON:", error.message);
}

Common Mistakes

  • Calling JSON.parse() on data that isn't actually a JSON string, causing an uncaught error.
  • Forgetting to wrap JSON.parse() in a try/catch when parsing data from an external, less trustworthy source like a user upload or third-party API.
  • Trying to parse a JavaScript object that's already been parsed once, rather than the raw JSON string.
  • Assuming parsed numbers keep their original formatting (e.g. leading zeros) — JSON.parse() converts them to native JavaScript numbers.

Professional Tip

Always wrap JSON.parse() calls on external data (API responses, file uploads, URL parameters) in a try/catch block. It's one of the most common places an unhandled exception can crash an otherwise working script.

Your Turn

Write a JavaScript function that safely parses a JSON string, returning the parsed object on success or a descriptive error message on failure.

Mini Quiz

What does JSON.parse() do when given a string that is not valid JSON?