简体   繁体   English

带有reviver函数的JSON.parse返回未定义

[英]JSON.parse with reviver function returns undefined

I am new to JSON and getting this exception while using reviver parameter in JSON.parse() : 我是JSON的新手,在JSON.parse()使用reviver参数时遇到此异常:

TypeError: Cannot read property 'name' of undefined(…).

Without reviver parameter code works fine but with reviver parameter it throws the above exception. 没有reviver参数代码可以正常工作,但使用reviver参数时,它将引发上述异常。 Why is that happening ? 为什么会这样呢?

 var str = ' { ' + ' "name" : "Username", ' + ' "fname" : "Fathername" ' + ' } '; var jObj = JSON.parse(str, function (a, b) { console.log(a + "=>" + b); }); document.write( "<h1>" + jObj.name + "</h1>", "<h2>" + jObj.fname + "</h2>" ); 

Because your reviver function returns implicitly undefined . 因为您的reviver函数隐式返回undefined

You have to return something, ie the variable b : 您必须返回一些东西,即变量b

 var str = JSON.stringify({ name: 'Username', fname: 'Fathername' }); var jObj = JSON.parse(str, function (a, b) { console.log(a, '=>', b); return b; }); document.write('<h1>' + jObj.name + '</h1>', '<h2>' + jObj.fname + '</h2>'); 

You just need to return the value in JSON.parse . 您只需要返回JSON.parse的值。 here is an example, with more pretty code: 这是一个带有更漂亮代码的示例:

 var str = '{"name": "Username", "fname": "Fathername"}'; var parsed = JSON.parse(str, (key, value) => { return value; }); document.write( "<h1>" + parsed.name + "</h1>", "<h2>" + parsed.fname + "</h2>" ); 

According to the reviver description on MDN : 按照reviver 在MDN说明

If the reviver function returns undefined (or returns no value, eg if execution falls off the end of the function), the property is deleted from the object. 如果reviver函数返回未定义的值(或不返回任何值,例如,如果执行落在函数的末尾),则从对象中删除该属性。

which is exactly what happens here. 这正是这里发生的情况。 Because there is no return statement in your reviver function, it implicitly returns undefined. 由于reviver函数中没有return语句,因此它隐式返回undefined。 Below you can see an equivalent: 在下面您可以看到一个等效项:

function (a,b) {
  console.log(a + "=>" + b);
  return undefined;
}

So in this scenario, JSON.parse actually parses your string to an object correctly, but then puts its properties through the reviver function, which returns undefined for all of them. 因此,在这种情况下, JSON.parse实际上将您的字符串正确解析为一个对象,然后通过reviver函数放置其属性,该函数针对所有对象返回未定义。 This results in undefined being returned. 这导致返回undefined

If you want to make it parse your object correctly, you might either return value explicitly: 如果要使其正确解析对象,则可以显式返回值:

var jObj = JSON.parse(str,function(a,b){
  console.log(a + "=>" + b);
  return b;
});

or remove reviver all together: 或一起移除齐磊:

var jObj = JSON.parse(str);

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

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