JSON parse reviver

2.8k views Asked by At

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;
});
2

There are 2 answers

0
Derek Pollard On

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.

0
IvanD On

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;
  }
  return value
});

console.log(jsonStructure);