JSON.parse()

ES5+

Parses a JSON string, constructing the JavaScript value or object described by the string.

Syntax

JSON.parse(text, reviver)

Parameters

text string

The string to parse as JSON

reviver Function optional

A function that transforms the results

Return Value

any

The JavaScript value corresponding to the given JSON text

Examples

JavaScript
const json = '{"name":"John","age":30}';
const obj = JSON.parse(json);
console.log(obj.name);
console.log(obj.age);
Output:
// 'John' 30

📌 When to Use

Use JSON.parse() when receiving data from APIs, reading from localStorage, processing configuration files, or deserializing any JSON-formatted strings.

⚠️ Common Mistakes

Not wrapping JSON.parse() in try-catch - invalid JSON throws a SyntaxError.

Assuming Date objects are preserved - they are parsed as strings and need a reviver to convert.

Using JSON.parse() on already-parsed objects, causing errors.

✅ Best Practices

Always validate or try-catch JSON.parse() for untrusted input to prevent crashes.

Use a reviver function to convert date strings back to Date objects.

⚡ Performance Notes

JSON.parse() is highly optimized in modern browsers. For very large JSON (>1MB), consider streaming parsers or Web Workers to avoid blocking the main thread.

🌍 Real World Example

Safe API Response Parser

Safely parse API responses with error handling and date conversion.

function parseApiResponse(jsonString) {
  const dateReviver = (key, value) => {
    // Convert ISO date strings to Date objects
    if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
      return new Date(value);
    }
    return value;
  };

  try {
    const data = JSON.parse(jsonString, dateReviver);
    return { success: true, data };
  } catch (error) {
    return {
      success: false,
      error: error.message,
      data: null
    };
  }
}

const response = '{"user":"John","createdAt":"2024-01-15T10:30:00.000Z"}';
const result = parseApiResponse(response);
console.log(result.data.createdAt instanceof Date); // true

Related Methods