6

给出以下示例:

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, ['company_name','address.street','address.example']));

如何使用 JSON 的 stringify 函数正确处理嵌套对象?

由于我有巨大的 JSON 对象,因此嵌套对象的键与其“父”对象相同。我想更详细地指定我的白名单。

4

2 回答 2

3

如果您愿意努力加入白名单,那么您可以建立一个有效键数组,它可以提供类似于多少系统进行 JSON 嵌套(.分隔符,或您选择的任何分隔符)的嵌套能力。

var 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;
}

我也有一个JSFiddle显示它的用法(以确保它在我公认的小样本集上实际工作)。

于 2013-07-06T21:15:34.157 回答
2

您可以在巨大的 JSON 对象中添加 toJSON 方法:

var test = {
    "company_name": "Foobar",
    "example": "HelloWorld",
    "address": {
        "street": "My Street 12",
        "example": "BarFoo",
        "details": "Berlin",
    },
    toJSON: function () {
        return {
            company_name: this.company_name,
            address: {
                street: this.address.street,
                example: this.address.example
            }
        }
    }
}

而且,你得到:

console.log(JSON.stringify(test)); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"

或者,您可以使用一些过滤功能:(此功能使用 lodash)

function filter(object, keys, sep) {
    sep = sep || '.';
    var result = {};
    _.each(keys, function (key) {
        var keyParts = key.split(sep),
            res = object, 
            branch = {},
            branchPart = branch;

        for (var i = 0; i < keyParts.length; i++) {
            key = keyParts[i];
            if (!_.has(res, key)) {
                return;
            }

            branchPart[key] = _.isObject(res[key]) ? {} : res[key];

            branchPart = branchPart[key];
            res = res[key];
        }

        _.merge(result, branch);
    });
    return result;    
}
console.log(JSON.stringify(filter(test, ['company_name', 'address.street', 'address.example']))); // "{"company_name":"Foobar","address":{"street":"My Street 12","example":"BarFoo"}}"

查看 jsfiddle http://jsfiddle.net/SaKhG/

于 2013-07-06T20:52:37.640 回答