如何在 Bash 中合并数千个 json 文档?

How to merge thousands of json documents in Bash?

我通过连接到某些 API 的脚本创建了超过 500 000 个 JSON 文档。我想将这些文件导入RethinkDB,但RethinkDB似乎无法导入大量文件,所以我想将所有这些文件合并成一个大JSON文件(比如bigfile.json)。这是它们的结构:

文件1.json:

{
  "key_1": "value_1.1",
  "key_2": "value_1.2",
  "key_3": "value_1.3",
    ...
  "key_n": "value_1.n"
}

文件2.json:

{
  "key_1": "value_2.1",
  "key_2": "value_2.2",
  "key_3": "value_2.3",
    ...
  "key_n": "value_2.n"
}
...

文件n.json:

{
  "key_1": "value_n.1",
  "key_2": "value_n.2",
  "key_3": "value_n.3",
    ...
  "key_n": "value_n.n"
}

我想知道创建大 JSON 文件的最佳结构是什么(为了完整起见,每个文件都有一个由 3 个变量组成的特定名称,第一个是时间戳 (YYYYMMDDHHMMSS)) ,以及哪个命令或脚本(直到现在我只为 bash...编写脚本)将允许我产生合并。

您提到了 bash,所以我假设您使用 *nix,您可以在其中使用 echocatsed 来实现您想要的。

$ ls   
file1.json  file2.json  merge_files.sh  output
$ cat file1.json 
{
    "key_1": "value_1.1",
    "key_2": "value_1.2",
    "key_3": "value_1.3",
    "key_n": "value_1.n"
}
$ ./merge_files.sh
$ cat output/out.json
{
"file1":
{
  "key_1": "value_1.1",
  "key_2": "value_1.2",
  "key_3": "value_1.3",
  "key_n": "value_1.n"
},
"file2":
{
  "key_1": "value_2.1",
  "key_2": "value_2.2",
  "key_3": "value_2.3",
  "key_n": "value_2.n"
}
}

下面的脚本读取文件夹中的所有 json 个文件,并将它们连接成一个 'big' 文件,文件名作为键。

#!/bin/bash

# create the output directory (if it does not exist)
mkdir -p output
# remove result from previous runs
rm output/*.json
# add first opening bracked
echo { >> output/tmp.json
# use all json files in current folder
for i in *.json
do 
    # first create the key; it is the filename without the extension
    echo \"$i\": | sed 's/\.json//' >> output/tmp.json
    # dump the file's content
    cat "$i" >> output/tmp.json
    # add a comma afterwards
    echo , >>  output/tmp.json
done
# remove the last comma from the file; otherwise it's not valid json
cat output/tmp.json | sed '$ s/.$//' >> output/out.json
# remove tempfile
rm output/tmp.json
# add closing bracket
echo } >> output/out.json

可以在 linux 上使用单个命令行完成。在所有 json 文件所在的目录中,创建一个新目录(比如 "output"),然后启动

jsonlint -v -f *.json > output/bigfile.json

jsonlint source

Jsonlint manual for ubuntu

如果您需要将一堆 JSON 文件作为单个对象读入内存,文件名作为键,内容作为相应的值,请考虑使用 jq:

jq -n '[inputs|{(input_filename):.}]|add' FILE...