【问题标题】:In jq update json when passing value as a variable在将值作为变量传递时在jq更新json
【发布时间】:2021-06-30 02:30:04
【问题描述】:

变量$task_definition 包含json 内容。我需要更新该 json 中的特定值。变量$docker_image 包含图像名称的值。当下面的脚本被执行时,它会放置变量名而不是变量$docker_image 的值。我如何让它把变量的值。

jq '.taskDefinition.containerDefinitions[0].image = "$docker_image"' <<< "$task_definition" > task-definition.json

输出:

{
  "taskDefinition": {
    "taskDefinitionArn": "arn:aws:ecs:us-east-1:123454566788:task-definition/nodejs-webapp:21",
    "containerDefinitions": [
      {
        "name": "webapp",
        "image": "$docker_image",
      }
    ]
  }
}

【问题讨论】:

标签: jq


【解决方案1】:

问题是您的 jq 表达式中的 $docker_image 周围有引号,并且需要像这样定义参数:

--arg &lt;variable_name&gt; &lt;variable_value&gt;

实际值同上:

--arg docker_image "b6fa739cedf5"


有了这些知识,您可以执行以下操作:

jq -r --arg docker_image "b6fa739cedf5" '.taskDefinition.containerDefinitions[0].image = $docker_image' <<< $task_definition > task-definition.json

我必须修复"image": "$docker_image"之后的多余逗号

我复制的步骤:

$ export task_definition='{
>   "taskDefinition": {
>     "taskDefinitionArn": "arn:aws:ecs:us-east-1:123454566788:task-definition/nodejs-webapp:21",
>     "containerDefinitions": [
>       {
>         "name": "webapp",
>         "image": "$docker_image"
>       }
>     ]
>   }
> }'

$ jq -r --arg docker_image "b6fa739cedf5" '.taskDefinition.containerDefinitions[0].image = $docker_image' <<< $task_definition > task-definition.json

$ cat task-definition.json
cat task-definition.json
{
  "taskDefinition": {
    "taskDefinitionArn": "arn:aws:ecs:us-east-1:123454566788:task-definition/nodejs-webapp:21",
    "containerDefinitions": [
      {
        "name": "webapp",
        "image": "b6fa739cedf5"
      }
    ]
  }
}

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2021-12-11
    • 2017-10-14
    • 2017-02-22
    • 2019-03-14
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多