2

使用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 }
]

什么是正确的米勒命令?

4

1 回答 1

0

弄清楚了。

你需要使用--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
   }
]
于 2022-01-10T00:31:51.710 回答