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

问题描述

给出如下数据:

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中显式调用它

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...