【问题标题】:Jq update JSON key:value based on valuejq根据value更新json key:value
【发布时间】:2016-08-01 23:52:51
【问题描述】:

我对 jq 还是很陌生,想用它来更新 AWS ECS 任务定义的新值。 AWS cli 返回以下 json 响应,我想用 name 属性 CONFIG_URL 用 value “this is atest”修改对象。

{
  "family": "contentpublishing-task",
  "volumes": [],
  "containerDefinitions": [
    {
      "environment": [
        {
          "name": "TEST_ENV",
          "value": "TEST"
        },
        {
          "name": "CONFIG_URL",
          "value": "s3://stg-appcfg/config-20160729-1130.json"
        }
      ],
      "name": "contentpublishing",
      "mountPoints": [],
      "image": "contentpublishing:blah",
      "cpu": 512,
      "portMappings": [
        {
          "protocol": "tcp",
          "containerPort": 8081,
          "hostPort": 8080
        }
      ],
      "memory": 256,
      "essential": true,
      "volumesFrom": []
    }
  ]
}

尝试了以下查询

 cat test.json | jq 'select(.containerDefinitions[0].environment[].name=="CONFIG_URL").value|="this is atest"' 2>&1 

但以下已返回。如您所见,在最外层的 json 对象中添加了一个附加值键。

{
  "family": "contentpublishing-task",
  "volumes": [],
  "containerDefinitions": [
    {
      "environment": [
        {
          "name": "TEST_ENV",
          "value": "TEST"
        },
        {
          "name": "CONFIG_URL",
          "value": "s3://stg-appcfg/config-20160729-1130.json"
        }
      ],
      "name": "contentpublishing",
      "mountPoints": [],
      "image": "contentpublishing:blah",
      "cpu": 512,
      "portMappings": [
        {
          "protocol": "tcp",
          "containerPort": 8081,
          "hostPort": 8080
        }
      ],
      "memory": 256,
      "essential": true,
      "volumesFrom": []
    }
  ],
  "value": "this is atest"
}

【问题讨论】:

    标签: json jq amazon-ecs


    【解决方案1】:

    在设置值之前,您必须先选择相应的环境节点。您的查询不会更改上下文,因此它仍在根项上,因此您最终将新值添加到根项。

    $ jq --arg update_name "CONFIG_URL" --arg update_value "this is a test" \
    '(.containerDefinitions[].environment[] | select(.name == $update_name)).value = $update_value' input.json
    

    【讨论】:

      【解决方案2】:

      这是一个使用 jq Complex assignments的解决方案

      (
        .containerDefinitions[]
      | .environment[]
      | select(.name == "CONFIG_URL")
      | .value
      ) |= "this is atest"
      

      【讨论】:

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