JSON.parse() with reviver
ES5+Uses a reviver function to transform values during JSON parsing.
Syntax
JSON.parse(text, reviver)Parameters
text string The string to parse as JSON
reviver Function A function that receives key and value, and returns the transformed value
Return Value
The transformed JavaScript value
Examples
const json = '{"created":"2024-01-15","count":"42"}';
const obj = JSON.parse(json, (key, value) => {
if (key === 'created') return new Date(value);
if (key === 'count') return parseInt(value, 10);
return value;
});
console.log(obj.created instanceof Date);
console.log(typeof obj.count); 📌 When to Use
Use a reviver function when parsing JSON that contains date strings, numeric strings that should be numbers, or any values that need type conversion.
⚠️ Common Mistakes
Not returning the value from the reviver, which replaces it with undefined.
Modifying nested objects before their children are processed - reviver processes bottom-up.
✅ Best Practices
Use ISO 8601 date format detection: /^\d{4}-\d{2}-\d{2}T/.test(value) for reliable date parsing.
⚡ Performance Notes
The reviver is called for every value, so keep pattern matching efficient. For large datasets, consider transforming after parsing.
🌍 Real World Example
Type-Safe JSON Parser
Parse JSON with automatic type conversion for dates and numeric strings.
function typedParse(jsonString) {
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
return JSON.parse(jsonString, (key, value) => {
// Convert ISO date strings to Date objects
if (typeof value === 'string' && isoDatePattern.test(value)) {
const date = new Date(value);
return isNaN(date.getTime()) ? value : date;
}
// Convert numeric strings (from certain APIs)
if (key === 'count' || key === 'total' || key === 'amount') {
const num = Number(value);
return isNaN(num) ? value : num;
}
return value;
});
}
const json = '{"created":"2024-01-15T10:30:00Z","count":"42","name":"Test"}';
const parsed = typedParse(json);
console.log(parsed.created instanceof Date); // true
console.log(typeof parsed.count); // "number"