json - 将 JSON 行序列 (JSONL) 转换为 JSON 数组

标签 json bash jq jsonlines

我有一个文件,其中每一行都是一个 JSON 对象。我想将文件转换为 JSON 数组。

文件看起来像这样:

{"address":"email1@foo.bar.com", "topic":"Some topic."}
{"address":"email2@foo.bar.com", "topic":"Another topic."}
{"address":"email3@foo.bar.com", "topic":"Yet another topic."}

我正在使用 bash 和 jq。

我试过了

jq --slurp --raw-input 'split("\n")[:-1]' my_file

但这只是将每一行视为一个字符串,创建一个 JSON 字符串数组。

[
  "{\"address\":\"email1@foo.bar.com\", \"topic\":\"Some topic.\"}",
  "{\"address\":\"email2@foo.bar.com\", \"topic\":\"Another topic.\"}",
  "{\"address\":\"email3@foo.bar.com\", \"topic\":\"Yet another topic.\"}"
]

我想要:

[
  {"address":"email1@foo.bar.com", "topic":"Some topic."},
  {"address":"email2@foo.bar.com", "topic":"Another topic."},
  {"address":"email3@foo.bar.com", "topic":"Yet another topic."}
]

最佳答案

jq -n '[inputs]' <in.jsonl >out.json

...或者,如 suggested by @borrible :

jq --slurp . <in.jsonl >out.json

关于json - 将 JSON 行序列 (JSONL) 转换为 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60637859/

相关文章:

bash - 使用 awk 将大型复杂的一列文件拆分为多列

bash - 杀死一系列进程

json - 使用 jq 或 Python 解析 JSON

arrays - 使用 jq 循环遍历 json 以获取多个值

javascript - 如何减少 JSON stringify 中数字的重要性

json - 使用 jq 有条件地修改嵌套的 json

Bash 通过作为参数传递的命令访问循环变量

Json 提取键的字段名称列表

jquery - 遍历 JSON

ruby-on-rails - 将静态 JSON 数据导出到 Amazon S3 并通过 AJAX 检索它