简体   繁体   中英

Strange behavior of JSON.parse() reviver function

I am using second parameter of JSON.parse() to modify the result, but I don't quite clear about the order of the function parameter and also how it work

I have read the document about the using of the reviver function (eg https://www.ecma-international.org/ecma-262/6.0/#sec-json.parse and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse ). From what I understand, this function would work with object, and first parameter is key or property name, second function is value or property value. What I don't understand is the return value of the function.

This is what it is done in example

 var obj1 = '{"a":1, "b":42}'; let text = JSON.parse(obj1, (key, value) => { if (typeof value === 'number'){ return value * 2 } else{ return value } } ) console.log(text) // {"a": 2, "b": 84} 

This work well. But when I try to modify the code since I know all value is number already

 var obj1 = '{"a":1, "b":42}'; let text = JSON.parse(obj1, (key, value) =>{ return value * 2 }) console.log(text) // NaN 

It is strange to me why when I delete the return value it doesn't work. I mean, with the function none of the value return undefined when I value*2 it. I then try another test

  var obj1 = '{"a":1, "b":42}'; let text = JSON.parse(obj1, (key, value) => { if (typeof value === 'number'){ console.log('This is in if',key, value) return value * 2 } else{ console.log('This is in else', key, value) return value } } ) console.log(text) 

Another strange thing happen when the code in else statement run even when it suppose not to run because the condition is incorrect. And when it run it even print out the obj1 object, which I didn't include in the statement.

Because it will also iterate thorough the object which is {"a":1, "b":42} .It will start from most nested level and then will go the original value itself which is {"a":1, "b":42} .

According to MDN

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

By the way you can shorten your function.

 var obj1 = '{"a":1, "b":42}'; let text = JSON.parse(obj1, (_, value) => value * 2 || value) console.log(text) 

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