开发者社区> 问答> 正文

jq +更新json文件并根据ID号附加名称

我们要根据以下规则编辑json文件

我们需要生成名称car0X_hyb.com -在mazda 字符串下(而X是ID号)

我们需要在我们的Linux机器上更新json文件

范例- ID=1

然后json将为

{
  "toyota": [
    "car1.com"
  ],
  "mazda": [
    "car01_hyb.com"
  ],
  "ford": [
    "car01_eng.com"
  ]
}
ID=4 ,那么json将为

{
  "toyota": [
    "car1.com"
  ],
  "mazda": [
    "car01_hyb.com",
    "car02_hyb.com",
    "car03_hyb.com",
    "car04_hyb.com"
  ],
  "ford": [
    "car01_eng.com"
  ]
}
ID=6 ,那么json将为

{
  "toyota": [
    "car1.com"
  ],
  "mazda": [
    "car01_hyb.com",
    "car02_hyb.com",
    "car03_hyb.com",
    "car04_hyb.com",
    "car05_hyb.com",
    "car06_hyb.com"
  ],
  "ford": [
    "car01_eng.com"
  ]
}
ID=10 ,那么json将为

{
  "toyota": [
    "car1.com"
  ],
  "mazda": [
    "car01_hyb.com",
    "car02_hyb.com",
    "car03_hyb.com",
    "car04_hyb.com",
    "car05_hyb.com",
    "car06_hyb.com",
    "car07_hyb.com",
    "car08_hyb.com",
    "car09_hyb.com",
    "car10_hyb.com"
  ],
  "ford": [
    "car01_eng.com"
  ]
}

展开
收起
祖安文状元 2020-01-16 17:42:38 510 0
1 条回答
写回答
取消 提交回答
  • 您可以使用生成后续数字流range,使用它们填充模板字符串,并根据结果组成一个数组,例如:

    $ jq -n --argjson ID 5 '.mazda = [ range($ID) | "car\("0\(.+1)"[-2:])_hyb.com" ]'
    {
      "mazda": [
        "car01_hyb.com",
        "car02_hyb.com",
        "car03_hyb.com",
        "car04_hyb.com",
        "car05_hyb.com"
      ]
    }
    $ jq -n --argjson ID 10 '.mazda = [ range($ID) | "car\("0\(.+1)"[-2:])_hyb.com" ]'
    {
      "mazda": [
        "car01_hyb.com",
        "car02_hyb.com",
        "car03_hyb.com",
        "car04_hyb.com",
        "car05_hyb.com",
        "car06_hyb.com",
        "car07_hyb.com",
        "car08_hyb.com",
        "car09_hyb.com",
        "car10_hyb.com"
      ]
    }
    
    

    根据in字符的最大长度调整前导0s和。-2ID

    2020-01-16 17:42:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载