JSON JQ查找替换值

时间:2016-06-08 09:54:14

标签: json jq

我正在尝试更新" image_id" json结构中的值。使用以下命令,如何将ami-d8cf5cab更改为ami-a4df7gah到目前为止,我已尝试过此操作

cat cog.test.tfstate | jq -r '.modules[].resources[] | select(.type == "aws_launch_configuration") | select(.primary.attributes.name_prefix == "pmsadmin-lc-")'

JSON数据是

{
  "type": "aws_launch_configuration",
  "primary": {
    "id": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
    "attributes": {
      "associate_public_ip_address": "false",
      "ebs_block_device.#": "0",
      "ebs_optimized": "false",
      "enable_monitoring": "true",
      "ephemeral_block_device.#": "0",
      "iam_instance_profile": "cog-test-pmsadmin",
      "id": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
      "image_id": "ami-d8cf5cab",
      "instance_type": "t2.small",
      "key_name": "cog-test-internal",
      "name": "pmsadmin-lc-v47thk6rcrdgza6dujfzjatmju",
      "name_prefix": "pmsadmin-lc-",
      "root_block_device.#": "0",
      "security_groups.#": "4",
      "security_groups.1893851868": "sg-7ee7bf1a",
      "security_groups.2774384192": "sg-e2e7bf86",
      "security_groups.2825850029": "sg-86e6bee2",
      "security_groups.3095009517": "sg-f4e7bf90",
      "spot_price": "",
      "user_data": "ed03ac6642af8c97562b065c0b37f211b58ad0a2"
    }
  }
}

2 个答案:

答案 0 :(得分:7)

使用|=运算符指定属性:

jq -r '.modules[].resources[] | select(.type == "aws_launch_configuration") | select(.primary.attributes.name_prefix == "pmsadmin-lc-")| .primary.attributes.image_id |= "ami-a4df7gah"

答案 1 :(得分:-4)

在我看来,问题和(迄今为止)唯一的回答无法满足stackoverflow.com社区的质量期望,因此应该关闭。

除此之外,我不得不承认他们实际上得到了我正在寻找的解决方案。

因此,对于处于相同情况的每个人来说,这里的hek2mgl's response形式实际上是可行的,并且在没有过多水平滚动的情况下可读:

假设问题中的JSON代码段位于cog.test.tfstate

jq_filter='. | select(.type == "aws_launch_configuration")'
jq_filter+=' | select(.primary.attributes.name_prefix == "pmsadmin-lc-")'
jq_filter+=' | .primary.attributes.image_id |= "ami-a4df7gah"'

jq "${jq_filter}" cog.test.tfstate

使用的样本数据对于发现实际变化没有帮助,所以这里是差异之前/之后:

diff cog.test.tfstate <(jq "${jq_filter}" cog.test.tfstate)
13c13
<       "image_id": "ami-d8cf5cab",
---
>       "image_id": "ami-a4df7gah",