How to use JSON.parse() with reviver function for date parsing In JSON

In this approach we are using JSON.parse() with a custom reviver function. The function examines each key-value pair during parsing, enabling specific transformations, such as converting date strings to Date objects, before returning the parsed JSON object.

Example: In this example we parses a JSON string, converting the “foundedDate” property to a Date object using a reviver function. It then logs the “name” property and checks if “foundedDate” is a Date.

JavaScript
const jsonStringWithDate: string = `{
    "name": "w3wiki",
    "foundedDate": "2009-01-01T00:00:00.000Z"
}`;

const jsonObjectWithDate = JSON.parse(jsonStringWithDate, (key, value) => {
    if (key === 'foundedDate') {
        return new Date(value);
    }
    return value;
});

console.log(jsonObjectWithDate.name);
console.log(jsonObjectWithDate.foundedDate instanceof Date); 

Output:

w3wiki
true


How to Convert String to JSON in TypeScript ?

Converting a string to JSON is essential for working with data received from APIs, storing complex data structures, and serializing objects for transmission.

Below are the approaches to converting string to JSON in TypeScript:

Table of Content

  • Convert String to JSON Using JSON.parse()
  • Convert String to JSON Using eval()
  • Convert String to JSON Using Function Constructor
  • Using JSON.parse() with reviver function for date parsing

Similar Reads

Convert String to JSON Using JSON.parse()

In this approach, we will make use of JSON.parse() function which parses a JSON string and converts it into a JavaScript object. It takes a single argument, which is a valid JSON-formatted string....

Convert String to JSON Using eval()

In this approach, we will use eval() function which is a global function in JavaScript that evaluates a string of JavaScript code in the context from which it’s called....

Convert String to JSON Using Function Constructor

In this approach, we will use Function() constructor which creates a function that returns a Javascript Object parsed to it....

Using JSON.parse() with reviver function for date parsing

In this approach we are using JSON.parse() with a custom reviver function. The function examines each key-value pair during parsing, enabling specific transformations, such as converting date strings to Date objects, before returning the parsed JSON object....

Contact Us