How to parse JSON in JavaScript?

To parse JSON in JavaScript, use the JSON.parse() method, which converts a JSON string into a JavaScript object. Here’s a step-by-step guide:

1. Basic Parsing

const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);

console.log(obj.name); // "John"
console.log(obj.age);  // 30

2. Error Handling

Wrap in a try...catch block to handle invalid JSON:

try {
  const invalidJson = '{"name": "John", "age": 30,}'; // Trailing comma
  const obj = JSON.parse(invalidJson);
} catch (error) {
  console.error("Invalid JSON:", error.message); // SyntaxError
}

3. Reviver Function

Transform values during parsing (e.g., convert date strings to Date objects):

const jsonString = '{"dateOfBirth": "1990-01-01"}';
const obj = JSON.parse(jsonString, (key, value) => {
  if (key === 'dateOfBirth') return new Date(value);
  return value;
});

console.log(obj.dateOfBirth instanceof Date); // true

4. Parsing Arrays and Nested Objects

const complexJson = `
{
  "users": [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"}
  ],
  "metadata": {"page": 1, "total": 2}
}`;

const data = JSON.parse(complexJson);
console.log(data.users[0].name); // "Alice"
console.log(data.metadata.page); // 1

5. Fetching and Parsing API Data

When using fetch, leverage .json() for automatic parsing:

fetch('https://api.example.com/data')
  .then(response => response.json()) // Auto-parses JSON
  .then(data => console.log(data))
  .catch(error => console.error("Fetch error:", error));

Key Notes

  • Valid JSON Syntax: Keys must use double quotes ("), and trailing commas are invalid.
  • Security: JSON.parse() is safer than eval() as it doesn’t execute arbitrary code.
  • Unsupported Types: Functions, undefined, and comments are not valid in JSON.

Summary Table

Use CaseCode Example
Basic parsingconst obj = JSON.parse(jsonString);
Error handlingtry { ... } catch (error) { ... }
Convert datesUse a reviver function with JSON.parse()
Parse API responsesfetch().then(res => res.json())

Use JSON.parse() to safely convert JSON strings into JavaScript objects, and always validate the input to avoid errors.

Leave a Reply

Your email address will not be published. Required fields are marked *