代码之家  ›  专栏  ›  技术社区  ›  Sammitch

使用jq修改/删除嵌套/选定的值,并输出整个文档

  •  0
  • Sammitch  · 技术社区  · 7 月前

    我正在Terraform提供程序之间迁移,为了解决一个错误,我需要更改 tfstate 文件是巨大的JSON Blob。我已经将文件精简为最基本的形式,但我想更改为:

    {
      "resources": [
        {
          "provider": "something_else",
          "type": "foo"
        },
        {
          "provider": "provider[\"registry.terraform.io/eddycharly/kops\"]",
          "type": "kops_cluster",
          "instances": [{
            "attributes": {
              "another_attr": "hello world",
              "config_base": "s3://foo-bucket/bar-env",
              "config_store": ""
            }
          }]
        },
        {
          "provider": "something_else",
          "type": "foo"
        }
      ]
    }
    
    

    {
      "resources": [
        {
          "provider": "something_else",
          "type": "foo"
        },
        {
          "provider": "provider[\"registry.terraform.io/eddycharly/kops\"]",
          "type": "kops_cluster",
          "instances": [{
            "attributes": {
              "another_attr": "hello world",
              "config_store": [{
                "base": "s3://foo-bucket/bar-env"
              }]
            }
          }]
        },
        {
          "provider": "something_else",
          "type": "foo"
        }
      ]
    }
    
    

    为此,我想出了一个表达式:

    .resources[] | 
    select(
      .provider == "provider[\"registry.terraform.io/eddycharly/kops\"]" and
      .type == "kops_cluster"
    ) |
    .instances[].attributes |
    .config_base as $config_base |
    .config_store |= [{ "base":$config_base }] |
    del(.config_base)
    

    但最终的输出只是经过修改的 .resources[].instances[].attributes 块,而不是整个文档,例如:

    {
      "another_attr": "hello world",
      "config_store": [
        {
          "base": "s3://foo-bucket/bar-env"
        }
      ]
    }
    

    如何重新排列此表达式以输出整个文档?

    1 回复  |  直到 7 月前
        1
  •  1
  •   Sammitch    7 月前

    你正在寻找这样的东西:

    (
      .resources[] | 
      select(
        .provider == "provider[\"registry.terraform.io/eddycharly/kops\"]" and
        .type == "kops_cluster"
      ) |
      .instances[].attributes
    ) |= (
      .config_store = [{ base:.config_base }] |
      del(.config_base)
    )
    

    你需要在的左手边加括号 |= 以保留原始结构。