我在JSON中有一些数据,我想用JQ编辑。
mobile
。mobile
都有number
(显然是唯一的)而不是。 calls
制作的。total
来电(他们拥有的每部手机的来电总数)我试图在这里使用自解释变量。如果数据不够清楚,请告诉我。
[
{
"name": "Person1",
"mobiles": [{
"number": "11111",
"calls": 2
},{
"number": "22222",
"calls": 3
}],
"total": 5
},
{
"name": "Person2",
"mobiles": [{
"number": "33333",
"calls": 1
},{
"number": "44444",
"calls": 2
},{
"number": "55555",
"calls": 1
}],
"total": 4
}
]
我想要的是,给定一个手机号码而不是。在特定日期对该移动电话进行的呼叫,更新json(更新个人计数器和总计)
EG。让我们说数字444444
调用是5,那么最后的json应该是
[
{
"name": "Person1",
"mobiles": [{
"number": "11111",
"calls": 2
},{
"number": "22222",
"calls": 3
}],
"total": 5
},
{
"name": "Person2",
"mobiles": [{
"number": "33333",
"calls": 1
},{
"number": "44444",
"calls": 7 // previous value was 2, added 5 more
},{
"number": "55555",
"calls": 1
}],
"total": 9 // previous total was 4, added 5 more
}
]
我可以更新total
来电,但不能更新给定号码的个别来电
map(select(.mobiles[].number == "44444").total = .total + 5)
给出了
[
{
"name": "Person1",
"mobiles": [
{
"number": "11111",
"calls": 2
},
{
"number": "22222",
"calls": 3
}
],
"total": 5
},
{
"name": "Person2",
"mobiles": [
{
"number": "33333",
"calls": 1
},
{
"number": "44444",
"calls": 2 // How do I update this
},
{
"number": "55555",
"calls": 1
}
],
"total": 9 // This is correct
}
]
答案 0 :(得分:2)
要更新您正在探索的相关“来电”:
map( (.mobiles[] | select(.number == $number) | .calls) += $incr)
其中$ number和$ incr的值可以(例如)在命令行中指定,例如
jq --arg number 44444 --argjson incr 5 -f update.jq input.json
要更新相关的“总计”,您可以使用any/2
:
map( if any(.mobiles[]; .number == $number)
then .total += $incr
else .
end)
您可以通过将两个过滤器组合成一个map
来将这两个链接在一起,或者字面上,或者(可能更有效)。为了便于阅读和维护,您可能还需要定义辅助函数(即使用def
)。