简体   繁体   中英

JSON.parse with reviver function returns undefined

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

Because your reviver function returns implicitly undefined .

You have to return something, ie 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>'); 

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

According to the reviver description on 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.

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

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