我有多个JSON文件,我想合并成一个。有些具有相同的根元素,但具有不同的子元素。我不想重写子元素,但如果它们有相同的父元素,我也会扩展它们。我尝试过this answer,但它不起作用:
jq: error (at file2.json:0): array ([{"title":"...) and array ([{"title":"...) cannot be multipliedSample files and wanted result (Gist)
提前谢谢你。
发布于 2017-08-18 08:37:12
下面是一个递归解决方案,它使用group_by(.key)来决定合并哪些对象。如果.children更统一,这可能会更简单一些。有时它在样本数据中不存在,有时是不寻常的值[{}]。
def merge:
def kids:
map(
.children
| if length<1 then empty else .[] end
)
| if length<1 then {} else {children:merge} end
;
def mergegroup:
{
title: .[0].title
, key: .[0].key
} + kids
;
if .==[{}] then .
else group_by(.key) | map(mergegroup)
end
;
[ .[] | .[] ] | merge在使用-s选项运行时,如下所示
jq -M -s -f filter.jq file1.json file2.json它会产生以下输出。
[
{
"title": "Title1",
"key": "12345678",
"children": [
{
"title": "SubTitle2",
"key": "123456713",
"children": [
{}
]
},
{
"title": "SubTitle1",
"key": "12345679",
"children": [
{
"title": "SubSubTitle1",
"key": "12345610"
},
{
"title": "SubSubTitle2",
"key": "12345611"
},
{
"title": "DifferentSubSubTitle1",
"key": "12345612"
}
]
}
]
}
]如果对象在.children中的顺序很重要,那么可以在{children:merge}表达式中添加一个sort_by,例如{children:merge|sort_by(.key)}
发布于 2017-05-12 02:44:53
这里有一些东西可以重现你想要的结果。这绝不是自动的,在这个阶段它实际上是一个概念证明。
一个线条:
jq -s '. as $in | ($in[0][].children[].children + $in[1][].children[0].children | unique) as $a1 | $in[1][].children[1] as $s1 | $in[0] | .[0].children[0].children = ($a1) | .[0].children += [$s1]' file1.json file2.json多行分解(复制/粘贴):
jq -s '. as $in
| ($in[0][].children[].children + $in[1][].children[0].children
| unique) as $a1
| $in[1][].children[1] as $s1
| $in[0]
| .[0].children[0].children = ($a1)
| .[0].children += [$s1]' file1.json file2.json其中:
$in:file1.json和file2.json合并合并“input$a1:”array$s1:SubSubTitle subtitle object我怀疑this不工作的原因是因为您的模式不同,并且具有嵌套数组。
我发现这看起来很催眠,如果你能详细说明一下这个结构是如何固定的,以及要求是什么,那就太好了。
https://stackoverflow.com/questions/43764041
复制相似问题