【问题标题】:How to convert a CSV to JSON array using the Miller command line tool?如何使用 Miller 命令行工具将 CSV 转换为 JSON 数组?
【发布时间】:2022-01-10 08:31:51
【问题描述】:

使用Miller 命令行工具,我想将带有标题的CSV 文件转换为JSON 数组。

目前我正在使用这个命令:mlr --icsv --ojson cat sample.csv > sample.json

输出的是 JSON,但不是数组格式。

这是示例 CSV 输入:

Keyword, Weight, Quantity
Apple, 10, 2345
Orange, 23, 467
Banana, 2345, 2345

这是我从米勒那里得到的输出:

{ "Keyword": "Apple", "Weight": 10, "Quantity": 2345 }
{ "Keyword": "Orange", "Weight": 23, "Quantity": 467 }
{ "Keyword": "Banana", "Weight": 2345, "Quantity": 2345 }

如您所见,此输出是 JSON Lines,而不是数组格式。

我希望 JSON 是一个数组,像这样:

[
    { "Keyword": "Apple", "Weight": 10, "Quantity": 2345 },
    { "Keyword": "Orange", "Weight": 23, "Quantity": 467 },
    { "Keyword": "Banana", "Weight": 2345, "Quantity": 2345 }
]

什么是正确的米勒命令?

【问题讨论】:

    标签: miller


    【解决方案1】:

    想通了。

    您需要使用--jlistwrap

    所以完整的命令变成:mlr --icsv --ojson --jlistwrap cat sample.csv > sample.json

    哪个输出这个:

    [
    { "Keyword": "Apple", "Weight": 10, "Quantity": 2345 }
    ,{ "Keyword": "Orange", "Weight": 23, "Quantity": 467 }
    ,{ "Keyword": "Banana", "Weight": 2345, "Quantity": 2345 }
    ]
    

    它的格式不漂亮(逗号在错误的行上,并且没有缩进),但它是一个有效的 JSON 数组。

    在运行一个工具来自动格式化 JSON 之后,它看起来像这样:

    [
       {
          "Keyword":"Apple",
          "Weight":10,
          "Quantity":2345
       },
       {
          "Keyword":"Orange",
          "Weight":23,
          "Quantity":467
       },
       {
          "Keyword":"Banana",
          "Weight":2345,
          "Quantity":2345
       }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-07
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2016-11-09
      相关资源
      最近更新 更多