在运行时替换 json 中的值

San*_*rma 6 bash

我正在尝试在 json 中替换运行时的值,即

老的

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "myimage",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}
Run Code Online (Sandbox Code Playgroud)

新的应该是

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "new image",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}
Run Code Online (Sandbox Code Playgroud)
  • 旧值:-“图像”:“我的图像”
  • 新值:-“图像”:“新图像”

我想用 bash 做。有什么最好的办法吗?可以通过jq吗?

717*_*71u 10

您可以为此使用 jq:

jq '.containerDefinitions[].image="new image"' old.son
Run Code Online (Sandbox Code Playgroud)


小智 0

像这样的东西应该适合你:

oldValue='"image": "myimage"'
newValue=${oldValue//myimage/newImage}
echo newValue
Run Code Online (Sandbox Code Playgroud)

InoldValue应该是你的 json.