我正在尝试合并一个目录中的所有 json 文件(可以有很多)。
我知道如果只有2个文件,我可以使用
jq -s . file1.json file2.json
。但是当我尝试使用像jq -s . file*.json
这样的通配符时,它失败了。有什么想法吗?
试试这个:
jq -s add *.json > merged.json
答案 这是
jq
答案...有关更多信息,请参阅下面的解释:
s="*.json"; jq -s "`x=-1; n=$(ls $s | wc -l); while [ $((x++)) -lt $(($n-2)) ]; do printf ".[$x] * " ; done; printf ".[$(($n-1))]";`" $s
逐步说明
要使用
jq
合并两个 json 文件,请使用以下命令:
jq -s ".[0] * .[1]" file1.json file2.json
现在合并三个 json 文件:
jq -s ".[0] * .[1] * .[2]" file1.json file2.json file3.json
让我们遵循相同的逻辑并使用通配符概括 n 个文件。困难的部分是生成字符串
.[0] * .[1] ... .[n-1]
.
首先我们来求n。 n 是文件夹中 json 文件的数量。所以:
ls *.json | wc -l
现在让我们编写一个循环来构建字符串“.[1] * .. * .[a] * .[a+1] * .. * .[n-2] *”。该字符串的内核是
.[a] *
所以:
x=-1; n=$(ls *.json | wc -l); while [ $((x++)) -lt $(($n-2)) ]; do printf ".[$x] * " ; done;
好的,现在让我们添加最后一部分
.[n-1]
:
x=-1; n=$(ls *.json | wc -l); while [ $((x++)) -lt $(($n-2)) ]; do printf ".[$x] * " ; done; printf ".[$(($n-1))]";
现在让我们将该字符串传递给 jq 命令...并参数化 *.json,以便我们可以轻松地将其替换为我们想要的任何内容:
s="*.json"; jq -s "`x=-1; n=$(ls $s | wc -l); while [ $((x++)) -lt $(($n-2)) ]; do printf ".[$x] * " ; done; printf ".[$(($n-1))]";`" $s
瞧!
在等待jq的解决方案时,让我解决这个问题“......或任何工具?”
不同的人通过“合并”意味着不同的事情,因此假设这里是一个简单的递归 JSON 合并,然后使用
jtc
(另一个工具),解决方案将如下所示(对于任意数量的文件):
jtc -J / -w[0] -mi[1:] / -w[0] *.json
为了说明该解决方案,以下是它如何处理任意 JSON 文件:
bash $ jtc -tc file1.json
{
"days": {
"2020-05-18": { "seconds": 60 },
"2020-05-19": { "seconds": 30 },
"2020-05-20": { "seconds": 1400 }
},
"total": { "seconds": 1490 }
}
bash $ jtc -tc file2.json
{
"days": {
"2020-05-20": { "seconds": 95 },
"2020-05-21": { "seconds": 80 },
"2020-05-22": { "seconds": 120 }
},
"total": { "seconds": 295 }
}
bash $ jtc -J / -w[0] -mi[1:] / -w[0] -tc file*.json
{
"days": {
"2020-05-18": { "seconds": 60 },
"2020-05-19": { "seconds": 30 },
"2020-05-20": {
"seconds": [ 1400, 95 ]
},
"2020-05-21": { "seconds": 80 },
"2020-05-22": { "seconds": 120 }
},
"total": {
"seconds": [ 1490, 295 ]
}
}
bash $
标志仅用于以紧凑格式显示 JSON-tc
PS。碰巧我是
jtc
工具 - unix JSON 处理实用程序的创建者。
我的 JSON 文件包含 JSON 对象。
jq -s add *.json
不起作用,但以下有效
jq -s '.' *.json > merged.json