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.
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
Contact Us