简体   繁体   English

带有reviver参数的JSON.parse将对象字段列入白名单

[英]JSON.parse with reviver parameter to whitelist object fields

I am writing a Node.js server which needs to accept a stringified JSON object in one of its services. 我正在编写一个Node.js服务器,该服务器需要在其服务之一中接受字符串化的JSON对象。 I also want to whitelist certain fields in the JSON object. 我还想将JSON对象中的某些字段列入白名单。 Both of these tasks should be accomplishable using JSON.parse() with the reviver parameter . 这两个任务都应该可以通过使用带有reviver参数的JSON.parse()来完成。

For some reason, trying to whitelist fields based on the key returns undefined for me. 出于某种原因,尝试根据键将字段列入白名单对我来说undefined Curiously, I am able to successfully blacklist fields, as seen in this jsfiddle . 奇怪的是,我能够成功将字段列入黑名单,如本jsfiddle所示

JSON.parse示例代码 JSON.parse输出示例

Can anyone explain this behavior and fix the first console.log statement to return {a="A"} ? 谁能解释这种现象并修复第一个console.log语句以返回{a="A"}

The reviver callback is called for each property of the JSON object, including nested properties, and finally for the object itself. 对JSON对象的每个属性(包括嵌套属性),最后对对象本身,都调用reviver回调。 So the last call of the reviver callback will get key = '' and value = [the JSON object] as arguments. 因此,reviver回调的最后一次调用将获得key = ''value = [the JSON object]作为参数。 '' is not equal to 'a' , so your reviver callback returns undefined when it is called for the last time for the whole object. ''不等于'a' ,因此您的齐磊回调在最后一次为整个对象调用时返回undefined。 This is why you see undefined for your "whitelisting" approach. 这就是为什么您看到“白名单”方法未定义的原因。

Another problem will arise when you use your approach on nested objects: 当您对嵌套对象使用方法时,将出现另一个问题:

var test = "{\"a\": { \"a\": \"A\", \"d\": \"D\" }, \"b\": \"B\", \"c\": \"C\"}";

console.log(JSON.parse(test, function(key, val){ if (key === "a" || key === "") return val; }));
//  { a: { a: 'A' } }  <-- property d is missing

You could eg use lodash's _.pick or a JSON schema validator like ajv to whitelist properties. 你可以使用例如lodash的_.pick或JSON模式验证像ajv到白名单中的性能。 Or you could simply delete unwanted properties: 或者,您可以简单地删除不需要的属性:

var whitelist = ['a'];
for (var prop in jsonObject) {
    if (!jsonObject.hasOwnProperty(prop)) continue;
    if (whitelist.indexOf(prop) === -1) delete jsonObject[prop];
}

The reviver is called 3 times + 1 final time with key as empty to indicate the object has been parsed. Reviver被称为3次+1次最终时间,其键为空以指示对象已被解析。

    var test = "{\"a\": \"A\", \"b\": \"B\", \"c\": \"C\"}";
    var res = JSON.parse(test,function(key, val){
    console.log(key,key=="");
    if (key === "b" ) {
        return val;
    } else if (key==""){
        return val;
    }});
    console.log(res);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM