简体   繁体   中英

JSON parse reviver

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 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM