Problem
The issue here is that you're not returning any value if the key doesn't match year
, effectively making everything else undefined
Solution
We need to always ensure we're returning a value from our reviver:
var stringData = '{ "year": 2011, "month": 8, "day": 9, "hour": 5, "minute": 32 }';
var jsonStructure = JSON.parse(stringData, function (key, value) {
return key == "year" ? value + 5 : value;
});
console.log(jsonStructure)
Explanation
From the MDN documentation site:
Using the reviver parameter
If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. Then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. If the reviver function returns undefined (or returns no value, for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value.