我在一个shell脚本中使用jq来操作JSON文件。
我有2个文件,我希望将它们合并到一个文件中,同时在名称/值对中的名称相同时聚合(和)值。
例如:
Input1.json
[
{
"A": "Name 1",
"B": "1.1",
"C": "2"
},
{
"A": "Name 2",
"B": "3.2",
"C": "4"
}
]Input2.json
[
{
"A": "Name 2",
"B": "5",
"C": "6"
},
{
"A": "Name 3",
"B": "7",
"C": "8"
}
]预期结果:
Output.json
[
{
"A": "Name 1",
"B": "1.1",
"C": "2"
},
{
"A": "Name 2",
"B": "8.2",
"C": "10"
},
{
"A": "Name 3",
"B": "7",
"C": "8"
}
]我可以使用jq以外的其他工具,但我更愿意最终将解决方案保存在我可以从终端调用的shell脚本中。
任何帮助都是非常感谢的。谢谢。
发布于 2021-09-13 06:24:33
对于这样的问题,jq是很漂亮的:
$ jq -n '
reduce inputs[] as {$A,$B,$C} ({};
.[$A] |= {
$A,
B: (.B + ($B|tonumber)),
C: (.C + ($C|tonumber))
}
)
| map({
A,
B: (.B|tostring),
C: (.C|tostring)
})
' input1.json input2.json第一个还原从不同的"A“值创建到聚合结果对象的映射。然后,给定映射,将其转换为调整结果类型的结果对象数组。
发布于 2021-09-12 10:28:12
我可以使用
jq以外的其他工具,但我更愿意最终将解决方案保存在我可以从终端调用的shell脚本中。
您可以尝试一下JSON解析器西德尔:
$ xidel -se '
array{
let $src:=(json-doc("Input1.json")(),json-doc("Input2.json")())
for $name in distinct-values($src/A)
let $obj:=$src[A=$name]
return
if (count($obj) gt 1) then
map:merge(
$obj[1]() ! {
.:if ($obj[1](.) castable as decimal) then
string($obj[1](.) + $obj[2](.))
else
$obj[1](.)
}
)
else
$obj
}
'发布于 2021-09-10 21:01:01
有一种方法,但也有其他的:
jq -s '
def to_n: tonumber? // null;
def merge_values($x;$y):
if $x == $y then $x
elif $x == null then $y
elif $y == null then $x
else ($x|to_n) as $xn
| if $xn then ($y|to_n) as $yn | ($xn+$yn)|tostring
else [$x, $y]
end
end;
def merge($x;$y):
reduce ($x + $y |keys_unsorted)[] as $k (null;
.[$k] = merge_values($x[$k]; $y[$k]) );
INDEX(.[0][]; .A) as $in1
| INDEX(.[1][]; .A) as $in2
| ($in1 + $in2|keys_unsorted) as $keys
| reduce $keys[] as $k ([];
. + [merge($in1[$k]; $in2[$k]) ])
' input1.json inut2.jsonhttps://stackoverflow.com/questions/69137721
复制相似问题