简体   繁体   English

JSON 解析器

[英]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.我正在尝试将 JSON 对象列表解析为一个名为 jsonStructure 的变量,该变量带有一个 reviver 函数,该函数将 5 添加到 stringData 变量中的“年份”对象。 However, the variable returns undefined.但是,该变量返回 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这里的问题是,如果键与year不匹配,您将不会返回任何值,从而有效地使其他所有内容都未定义

Solution解决方案

We need to always ensure we're returning a value from our reviver:我们需要始终确保我们从我们的 revive 返回一个值:

 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:MDN 文档站点:

Using the reviver parameter使用reviver参数

If a reviver is specified, the value computed by parsing is transformed before being returned.如果指定了reviver,则解析计算出的值在返回之前会进行转换。 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.具体来说,计算值及其所有属性(从嵌套最多的属性开始并继续到原始值本身)单独运行通过 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.如果 reviver 函数返回 undefined(或不返回任何值,例如,如果执行在函数的末尾结束),则该属性将从对象中删除。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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