Programming Advanced

Use JSON.parse() with Reviver Function

Parsing JSON with dates or special types requires manual post-processing. Use the reviver parameter in JSON.parse() to transform values during parsing.

Problem

Parsing JSON with dates or special types requires manual post-processing.

Solution

Use the reviver parameter in JSON.parse() to transform values during parsing.

Benefit

Automates type conversion and eliminates separate transformation loops.

Code Example

const json = '{"date":"2024-01-01T00:00:00.000Z","count":"42"}';

const data = JSON.parse(json, (key, value) => {
    // Convert date strings to Date objects
    if (key === 'date') return new Date(value);
    // Convert numeric strings to numbers
    if (key === 'count') return parseInt(value);
    return value;
});

ES
Edrees Salih
6 hours ago

We are still cooking the magic in the way!