Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values in JSON with JQ and regex

Tags:

regex

jq

I have the following JSON where I want to change the "tag" of the "image" strings.

{
  "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"
  }
}

It should become:

{
  "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"
  }
}

Of course "latest" can be anything.

So far I've found the following regex sub to modify the strings.

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

But I want to edit them in place and keep the whole JSON. So far my attempts to change the value were unsuccessful. I can change the image value to a fixed string but not to the substituted original value.

I've tried several variations of this:

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

It seems like the version I can simply use (in Bitbucket pipelines) doesn't have the walk function, so I'd avoid it.

like image 800
Zsolt Fejér Avatar asked Mar 07 '19 16:03

Zsolt Fejér


1 Answers

Oh, just found it after a few more attemps

'.taskDefinition.containerDefinitions[].image |= sub("(?<repo>.*:).*"; "\(.repo)new")'
like image 162
Zsolt Fejér Avatar answered Sep 26 '22 22:09

Zsolt Fejér