[英]jq sum and multiply values to get an aggregate
Given the following JSON, is there a way to get the aggregated memory (sum of all memory values multiplied by the number of instances in each case) with a jq
query?给定以下 JSON,有没有办法通过
jq
查询获取聚合内存(所有内存值的总和乘以每种情况下的实例数)?
{
"apps": [
{
"memory": 512,
"instances": 3
},
{
"memory": 256,
"instances": 1
},
{
"memory": 128,
"instances": 6
},
{
"memory": 1024,
"instances": 2
}
]
}
In this example it should perform the following operation:在这个例子中,它应该执行以下操作:
512*3 + 256*1 + 128*6 + 1024*2
so it should give me 4608
in total.所以它总共应该给我
4608
。
Just for the record, I am using command line jq
in CentOS8:只是为了记录,我在 CentOS8 中使用命令行
jq
:
jq --version
jq-1.5
A one-liner solution:单线解决方案:
reduce .apps[] as $x (0; . + ($x | .memory * .instances))
Or more elegantly:或者更优雅:
def sigma(s): reduce s as $x (0; . + $x);
sigma(.apps[] | .memory * .instances)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.