jsondecode.com logo

HomeChevronBlogChevronJSON.parse() Complete Guide: Reviver Function, Error Handling, and Edge Cases

Blog post

JSON.parse() Complete Guide: Reviver Function, Error Handling, and Edge Cases

Master JSON.parse() in JavaScript — reviver functions for date revival, error handling patterns, safe parsing wrappers, and common pitfalls to avoid.

author

Shashank Jain

Author

22/05/20260 minutes 43 seconds read
JSON.parse() Complete Guide: Reviver Function, Error Handling, and Edge CasesJSON.parse() Complete Guide: Reviver Function, Error Handling, and Edge Cases

Article

What is JSON.parse()?

JSON.parse() parses a JSON string and returns the corresponding JavaScript value. It is the standard way to deserialize JSON from APIs, files, and storage.

Basic Usage

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

Always Wrap in Try/Catch

JSON.parse() throws a SyntaxError on invalid input. Never call it without error handling in production code.

function safeJsonParse(str, fallback = null) {
  try {
    return JSON.parse(str);
  } catch {
    return fallback;
  }
}

// Usage
const data = safeJsonParse(responseText, {});

The Reviver Function

The optional second argument to JSON.parse() is called for every key/value pair and lets you transform values during parsing.

// Auto-revive ISO date strings to Date objects
const data = JSON.parse(json, (key, value) => {
  if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value)) {
    return new Date(value);
  }
  return value;
});

Common Errors and Fixes

ErrorCauseFix
Unexpected token <Server returned HTML (404/500)Check res.ok before parsing
Unexpected token uInput is undefinedGuard: if (str) JSON.parse(str)
Unexpected end of JSONTruncated responseCheck Content-Length / streaming

Validate your JSON before parsing with the free JSON validator at jsondecode.com.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.