I'm trying to parse a list of JSON objects into a variable called jsonStructure with a reviver function which adds 5 to the 'year' object within the stringData variable. However, the variable returns undefined. I'm not sure what I'm doing wrong as I have the parser set up exactly as the book would have it set up. Here is my code below:
var stringData = '{ "year": 2011, "month": 8, "day": 9, "hour": 5, "minute": 32 }';
var jsonStructure = JSON.parse(stringData, function (key, value) {
if (key == "year")
return value + 5;
});
Problem
The issue here is that you're not returning any value if the key doesn't match
year
, effectively making everything else undefinedSolution
We need to always ensure we're returning a value from our reviver:
Explanation
From the MDN documentation site: