给出以下示例:
var test = {
"company_name": "Foobar","example": "HelloWorld","address": {
"street": "My Street 12","example": "BarFoo","details": "Berlin",}
}
console.log(JSON.stringify(test,['company_name','address','street','example']));
// What I actually want
// console.log(JSON.stringify(test,'address.street','address.example']));
如何使用JSON的stringify函数正确处理嵌套对象?
由于我有巨大的JSON对象,因此嵌套对象的键与它的“父”对象相同.我想更明确地指定我的白名单.
最佳答案
如果您愿意使用白名单,那么您可以建立一组有效密钥,这些密钥可以提供嵌套功能,类似于JSON嵌套的系统数量(a.分隔符,或您选择的任何分隔符) .
原文链接:https://www.f2er.com/js/429782.htmlvar whitelistedObj = whitelistJson(obj,["company_name","example","address.street","address.example"]);
function whitelistJson(obj,whitelist,separator) {
var object = {};
for (var i = 0,length = whitelist.length; i < length; ++i) {
var k = 0,names = whitelist[i].split(separator || '.'),value = obj,name,count = names.length - 1,ref = object,exists = true;
// fill in any empty objects from first name to end without
// picking up neighboring fields
while (k < count) { // walks to n - 1
name = names[k++];
value = value[name];
if (typeof value !== 'undefined') {
if (typeof object[name] === 'undefined') {
ref[name] = {};
}
ref = ref[name];
}
else {
exists = false;
break;
}
}
if (exists) {
ref[names[count]] = value[names[count]];
}
}
return object;
}