簡體   English   中英

jQuery更新JSON鍵:基於值的值

[英]Jq update JSON key:value based on value

我對jq相當陌生,想用它來用新值更新AWS ECS任務定義。 AWS cli返回以下json響應,我想用名稱屬性CONFIG_URL修改 值為 “ 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"
}

設置值之前,必須先選擇相應的環境節點。 您的查詢不會更改上下文,因此它仍在根項上,因此最終將新值添加到根中。

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

這是使用jq 復雜分配的解決方案

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM