【问题标题】:Nested JSON Objects: Remove reference to source level JSON in CSV Export嵌套 JSON 对象:在 CSV 导出中删除对源级 JSON 的引用
【发布时间】:2017-12-14 09:11:43
【问题描述】:

我正在构建一个将以下格式的 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 文件中的文本返回给浏览器之前。

【问题讨论】:

    标签: javascript json node.js csv


    【解决方案1】:
    [
        {
            "_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;
    });
    

    【讨论】:

    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 2021-12-25
    • 2020-12-27
    • 2020-04-03
    • 1970-01-01
    • 2021-08-21
    • 2016-12-11
    相关资源
    最近更新 更多