【问题标题】:Replacing values in JSON with JQ and regex用 JQ 和正则表达式替换 JSON 中的值
【发布时间】:2019-03-07 16:29:00
【问题描述】:

我有以下 JSON,我想在其中更改“图像”字符串的“标签”。

{
  "taskDefinition": {
    "containerDefinitions": [
      {
        "name": "php",
        "image": "xxxxxx.dkr.ecr.eu-west-1.amazonaws.com/repo/php:latest",
        "cpu": 0,
        "memory": 512
      },
      {
        "name": "nginx",
        "image": "xxxxxx.dkr.ecr.eu-west-1.amazonaws.com/repo/nginx:latest",
        "cpu": 0,
        "memory": 256
      }
    ],
    "family": "service-be"
  }
}

应该变成:

{
  "taskDefinition": {
    "containerDefinitions": [
      {
        "name": "php",
        "image": "xxxxxx.dkr.ecr.eu-west-1.amazonaws.com/repo/php:new",
        "cpu": 0,
        "memory": 512
      },
      {
        "name": "nginx",
        "image": "xxxxxx.dkr.ecr.eu-west-1.amazonaws.com/repo/nginx:new",
        "cpu": 0,
        "memory": 256
      }
    ],
    "family": "service-be"
  }
}

当然,“最新”可以是任何东西。

到目前为止,我已经找到了以下正则表达式子来修改字符串。

'.taskDefinition.containerDefinitions[].image | sub("(?<repo>.*:).*";  \(.repo)new")'

但我想编辑它们并保留整个 JSON。 到目前为止,我尝试更改该值的尝试均未成功。 我可以将图像值更改为固定字符串,但不能更改为替换的原始值。

我已经尝试了几种变体:

'.taskDefinition.containerDefinitions[].image |= . | sub("(?<repo>.*:).*"; "\(.repo)new")'

我可以简单使用的版本(在 Bitbucket 管道中)似乎没有 walk 功能,所以我会避免它。

【问题讨论】:

    标签: regex jq


    【解决方案1】:

    哦,多试几次才找到

    '.taskDefinition.containerDefinitions[].image |= sub("(?<repo>.*:).*"; "\(.repo)new")'
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多