如何使用jq的reduce
函数来处理多种操作?
给出一个像这样的模型:
{
"usage" : {
"os:linux" : {
"2018_11_18" : {
"amount" : 601046342,
"credits" : 99783
},
"2018_10_18" : {
"amount" : 839785106,
"credits" : 173121
}
}
}
}
和JQ文件:
reduce .usage."os:linux"[] as $item (
{"credits":0,"minutes":0};
."credits" += $item.credits
)
我得到:
{
"credits": 272904,
"minutes": 0
}
很酷,但是我想同时介绍两个领域,例如:
reduce .usage."os:linux"[] as $item (
{"credits":0,"minutes":0};
."credits" += $item.credits,
."minutes" += $item.amount /1000/60
)
分号会导致错误,逗号通过,但仅处理最后一个任务,即
{
"credits": 0,
"minutes": 24013.85746666667
}
答案 0 :(得分:1)
总有明确的方法:
reduce .usage."os:linux"[] as $item (
{"credits": 0, "minutes": 0 };
{
"credits": (.credits + $item.credits),
"minutes": (.minutes + $item.amount / 60000)
}
)
答案 1 :(得分:0)
或更简洁:
reduce .usage."os:linux"[] as $item (
{};
.credits += $item.credits
| .minutes += ($item.amount / 60000) )
或将简化形式抽象为通用工具功能sigma/1
:
def sigma(s): reduce s as $s (null; . + $s);
.usage."os:linux"
| {credits: sigma(.[].credits),
minutes: (sigma(.[].amount) / 60000) }