如何在jq中将更新与函数结果结合起来



给定的数据如下:

cat << EOF > xyz.json
[
{
"batch_id": 526,
"aCods": [
"IBDD879"
]
},
{
"batch_id": 357,
"aCods": [
"IBDD212"
]
}
]
EOF

获得此结果的正确方法是什么

[
{
"batch_id": "00000526",
"aCods": [
"IBDD879"
]
},
{
"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"

假设您正试图使用该峰值注释中的lpad/2,则可以执行

def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
map(.batch_id |= lpad(8; "0"))

这里的关键是,当使用更新分配运算符|=时,正在修改的字段会在内部传递,这样您就不必在RHS 中显式调用它

最新更新