问题描述
给出如下数据:
cat << EOF > xyz.json
[
{
"batch_id": 526,"aCods": [
"IBDD879"
]
},{
"batch_id": 357,"aCods": [
"IBDD212"
]
}
]
EOF
获得此结果的正确方法是什么?
[
{
"batch_id": "00000526",{
"batch_id": "00000357","aCods": [
"IBDD212"
]
}
]
我尝试了三种不同的命令,希望能够使用该元素上的函数结果来更新数组中的对象元素。
我只是找不到正确的语法。
jq -r '.[] | .batch_id |= 9999999' xyz.json;
{
"batch_id": 9999999,"aCods": [
"IBDD879"
]
}
{
"batch_id": 9999999,"aCods": [
"IBDD212"
]
}
jq -r '.[] | lpad("\(.batch_id)";8;"0")' xyz.json;
00000526
00000357
jq -r '.[] | .batch_id |= lpad("\(.batch_id)";8;"0")' xyz.json;
jq: error (at /dev/shm/xyz.json:14): Cannot index number with string "batch_id"
解决方法
假设您要尝试使用this peak’s comment中的lpad/2
,就可以
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
map(.batch_id |= lpad(8; "0"))
这里的关键是当使用更新分配运算符|=
时,正在修改的字段是在内部传递的,因此您不必在RHS中显式调用它