我有以下几点:



const whitelist = ['prop1', 'prop2', 'result'];
const reviver = (key, value) => {
  if (whitelist.includes(key)) {
    return value;
  } else {
    return undefined; // explicitly delete the entry
  }
};

const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }';

console.log(JSON.parse(theMightyJsonString))
console.log(JSON.parse(theMightyJsonString, reviver))





现在,我可以成功地JSON.parse(theMightyJsonString)进入对象,但是如果我像这样JSON.parse(theMightyJsonString, reviver)传递齐齐器,则结果为undefined

我想念什么?

最佳答案

对reviver的最后一次调用将使用一个空字符串作为键""进行,该键允许您将转换应用于最终对象(在您的情况下,您将其转换为undefined)。如果为空字符串添加测试,则它将正常工作:



const whitelist = ['prop1', 'prop2', 'result'];
const reviver = (key, value) => {
  if (whitelist.includes(key) || key === '') {
    return value;
  } else {
    return undefined; // explicitly delete the entry
  }
};

const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }';

console.log( JSON.parse( theMightyJsonString, reviver ) );

10-06 03:17