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

The Reviver Parameter

Using the second parameter of JSON.parse to transform values during parsing, like converting date strings.

The Reviver Parameter

What you'll learn: How to use the second parameter of JSON.parse() to transform values as they're being parsed, turning strings back into the correct data types.

The Problem JSON Can't Solve Alone

When you use JSON.parse(), it converts JSON strings into JavaScript objects, but it can't automatically recognize special types like dates. A date stored as "2024-01-15T10:30:00Z" comes back as a plain string, not a Date object.

Enter the Reviver Function

The reviver parameter is an optional second argument to JSON.parse(). It's a function that gets called for every key-value pair during parsing, letting you transform values on the fly.

const jsonString = '{"name":"Alice","joined":"2024-01-15T10:30:00Z"}';

const user = JSON.parse(jsonString, function(key, value) {
  // Check if the value looks like a date string
  if (key === 'joined' && typeof value === 'string') {
    return new Date(value); // Transform string → Date
  }
  return value; // Leave other values unchanged
});

console.log(user.joined instanceof Date); // true
console.log(user.joined.getFullYear());   // 2024

How It Works

Think of the reviver like a customs inspector: as each piece of data enters JavaScript from JSON, the reviver examines it and can modify it before letting it through. The function receives two arguments: the property key and its value, and whatever you return becomes the final value.

The reviver is called for every property, including nested objects, from innermost to outermost, ending with an empty key "" for the root object.

Key Takeaway: The reviver parameter transforms JSON values during parsing, solving problems like converting date strings back into Date objects automatically.