我想使用jq来汇总具有相同描述字段值的元素。 这样,每个描述的唯一字段值都将获得其自己的元素,并汇总了数量字段。
我正在使用jq 1.5
之前:
{ "frames":
[
{ "description": "Stuff", "amount": 8 },
{ "description": "Stuff", "amount": 4 },
{ "description": "other_stuff", "amount": 2 },
{ "description": "more_stuff", "amount": 20 }
]
}
之后:
{ "frames":
[
{ "description": "Stuff": 12 },
{ "description": "other_stuff", "amount": 2 },
{ "description": "more_stuff", "amount": 20 }
]
}
答案 0 :(得分:1)
根据您的输入,以下程序将根据问题的精神生成有效的JSON:
def sum_by(f;g): reduce .[] as $x ({}; .[$x|f] += ($x|g));
.frames |= sum_by(.description; .amount)
由于各种原因,使用sum_by
比使用group_by
更有效。
{
"frames": {
"Stuff": 12,
"other_stuff": 2,
"more_stuff": 20
}
}
如果您想在输出中使用description
和amount
,可以对上述内容进行如下调整:
.frames |=
(sum_by(.description; .amount)
| to_entries
| map( {description: .key, amount: .value} ))
输出将是:
{
"frames": [
{
"description": "Stuff",
"amount": 12
},
{
"description": "other_stuff",
"amount": 2
},
{
"description": "more_stuff",
"amount": 20
}
]
}