在javascript中展平json数据结构

Hor*_*ice -1 javascript

我有一个json响应来自一个有点痛苦的服务.我怎样才能将这个结构扁平化,以便 "not_restricted":{"doc_count": 976465}改为"not_restricted":976465?我会使用一个函数来检测所有类型的json文档中的这种结构并修改结果.

这是json的一般结构:

{
    "took": 159,
    "timed_out": false,
    "_shards": {
        "total": 6,
        "successful": 6,
        "failed": 0
    },
    "hits": {
        "total": 4909332,
        "max_score": 1,
        "hits": [
            {
                ...
            },
            {
                ...
            },
            {
                ...
            }
        ]
    },
    "aggregations": {
        "index_types": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
                {
                    "key": "client",
                    "doc_count": 1958205,
                    "not_restricted": {
                        "doc_count": 976465
                    },
                    "restricted": {
                        "doc_count": 981740
                    }
                },
                {
                    "key": "ultimateparent",
                    "doc_count": 1616164,
                    "not_restricted": {
                        "doc_count": 741059
                    },
                    "restricted": {
                        "doc_count": 875105
                    }
                },
                {
                    "key": "facility",
                    "doc_count": 1334963,
                    "not_restricted": {
                        "doc_count": 914090
                    },
                    "restricted": {
                        "doc_count": 420872
                    }
                }
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 5

您可以使用reviver参数ofJSON.parse来轻松完成此操作,该参数允许您过滤JSON中的每个对象:

var res = JSON.parse(json, function(k, o) {
    if (Object(o) !== o) return o; // primitive values
    var keys = Object.keys(o);
    if (keys.length == 1 && keys[0] == "doc_count")
        return o.doc_count;
    else
        return o;
});
Run Code Online (Sandbox Code Playgroud)

如果要确保仅在此类属性中替换单例,您还可以测试k包含"restricted"左右doc_count.