简体   繁体   中英

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. I also want to whitelist certain fields in the JSON object. Both of these tasks should be accomplishable using JSON.parse() with the reviver parameter .

For some reason, trying to whitelist fields based on the key returns undefined for me. Curiously, I am able to successfully blacklist fields, as seen in this jsfiddle .

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

Can anyone explain this behavior and fix the first console.log statement to return {a="A"} ?

The reviver callback is called for each property of the JSON object, including nested properties, and finally for the object itself. So the last call of the reviver callback will get key = '' and value = [the JSON object] as arguments. '' is not equal to 'a' , so your reviver callback returns undefined when it is called for the last time for the whole object. 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. 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.

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

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