【问题标题】:How to combine update with function result in jq?如何在jq中将更新与函数结果结合起来?
【发布时间】:2021-01-02 12:02:15
【问题描述】:

给定这样的数据:

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"

【问题讨论】:

    标签: json jq zero-padding


    【解决方案1】:

    假设您尝试使用来自this peak’s commentlpad/2,您可以这样做

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

    这里的关键是当使用更新赋值运算符|=时,被修改的字段是在内部传递的,所以你不必在RHS中显式调用它

    【讨论】:

    • 奖金结果!我对 jq 函数名称后面的 /2 和 /3 感到困惑;它们表示所需参数的数量,对吗?感谢您快速清晰有效且内容丰富的答案。谢谢!
    • @MartinBramwell :您对 jq 函数的 /n 表示法是正确的。很高兴答案有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2018-04-24
    • 1970-01-01
    • 2010-11-13
    • 2021-08-06
    相关资源
    最近更新 更多