JSON.parse with reviver function returns undefined

≡放荡痞女 提交于 2021-01-29 04:32:06

问题


I am new to JSON and getting this exception while using reviver parameter in JSON.parse():

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

Without reviver parameter code works fine but with reviver parameter it throws the above exception. 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>"
);

回答1:


Because your reviver function returns implicitly undefined.

You have to return something, i.e. the variable 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>');



回答2:


You just need to return the value in 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>"
 );
 



回答3:


According to the reviver description on MDN:

If the reviver function returns undefined (or returns no value, e.g. if execution falls off the end of the function), the property is deleted from the object.

which is exactly what happens here. Because there is no return statement in your reviver function, it implicitly returns 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. This results in undefined being returned.

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


来源:https://stackoverflow.com/questions/41211345/json-parse-with-reviver-function-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!