我有以下内容:
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)
进入一个对象了,但是如果像这样传入reviver,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 ) );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句