嵌套JSON对象:在CSV导出中删除对源级JSON的引用

时间:2017-07-10 14:56:21

标签: javascript json node.js csv

我正在构建一个应用程序,将以下格式的JSON转换为CSV:

[
{
    "_type":  "End",
    "_source": {
        "timestamp_milli": 1499696661704,
        "timestamp": "2017-07-10T14:24:21.704Z",
        "country": "United States",
        "country-code": "US"
    }
},
{
    "_type": "Info",
    "_source": {
        "timestamp_milli": 1499696614807,
        "timestamp": "2017-07-10T14:23:34.807Z",
        "country": "United States",
        "country-code": "US"
    }
},
{
    "_type": "Menu",
    "_source": {
        "timestamp_milli": 1499696578167,
        "timestamp": "2017-07-10T14:22:58.167Z",
        "country": "United States",
        "country-code": "US"
    }
}
]

现在我正在使用jsonexport npm包,它以下列形式为上述JSON文档生成一个CSV文件:

_type,_source.timestamp_milli,_source.timestamp,_source.country,_source.country-code
End,1499696661704,2017-07-10T14:24:21.704Z,United States,US
Info,1499696614807,2017-07-10T14:23:34.807Z,United States,US
Menu,1499696578167,2017-07-10T14:22:58.167Z,United States,US

我试图删除“_source”。生成的.csv文件的标头中的文本。 JSON文档将始终具有相同的结构,但“_source”中的元素将根据用户输入而更改。我试图在不对JSON中的任何密钥进行硬编码的情况下实现此目的。

有人可以帮我找出使用node.js的最佳方法吗?我有一些不同的想法是从JSON文档中删除“_source”级别,或修剪“_source”。在将其返回浏览器之前,来自csv文件的文本。

1 个答案:

答案 0 :(得分:2)

[
    {
        "_type" : "End",
        "_source" : {
            "timestamp_milli" : 1499696661704,
            "timestamp" : "2017-07-10T14:24:21.704Z",
            "country" : "United States",
            "country-code" : "US"
        }
    },
    {
        "_type" : "Info",
        "_source" : {
            "timestamp_milli" : 1499696614807,
            "timestamp" : "2017-07-10T14:23:34.807Z",
            "country" : "United States",
            "country-code" : "US"
        }
    },
    {
        "_type" : "Menu",
        "_source" : {
            "timestamp_milli" : 1499696578167,
            "timestamp" : "2017-07-10T14:22:58.167Z",
            "country" : "United States",
            "country-code" : "US"
        }
    }
].map((item) => {
    // assign nested properties from _source
    Object.assign(item, item._source);
    // remove _source from item
    delete item._source;
});