繁体   English   中英

如何使用 jq 删除嵌套键值对,其值具有更深的嵌套数组和特定值

[英]How can I remove a nested key-value pair, whose value has a deeper nested array with a specific value by using jq

我目前正在尝试使用 jq 从 swagger json 文档中过滤掉一些路径值。

JSON 看起来像这样:

{
  "swagger": "2.0",
  "info": {
    "version": "1.0.2",
    "title": "Some API"
  },
  "host": "example.com",
  "basePath": "/",
  "paths": {
    "/api/companies": {
      "get": {
        "tags": [ "company-tag" ],
        "responses": {
          "200": {
            "description": "OK",
            "schema": { "$ref": "#/definitions/CompanyDTO" }
          }
        }
      }
    },
    "/api/account": {
      "get": {
        "tags": [ "account-tag" ],
        "operationId": "getAccount",
        "responses": {
          "200": {
            "description": "OK",
            "schema": { "$ref": "#/definitions/UserDTO" }
          }
        }
      },
      "post": {
        "tags": [ "account-tag" ],
        "operationId": "createAccount",
        "responses": {
          "200": {
            "description": "OK",
            "schema": { "$ref": "#/definitions/UserDTO" }
          }
        }
      }
    }
  }
}

我想过滤路径值,以便我只能获取标签数组中包含特定标签的路径。

例如:如果我想获取帐户标签的路径,则 JSON 在过滤后应该如下所示:

{
  "swagger": "2.0",
  "info": {
    "version": "1.0.2",
    "title": "Some API"
  },
  "host": "example.com",
  "basePath": "/",
  "paths": {
    "/api/account": {
      "get": {
        "tags": [ "account-tag" ],
        "operationId": "getAccount",
        "responses": {
          "200": {
            "description": "OK",
            "schema": { "$ref": "#/definitions/UserDTO" }
          }
        }
      },
      "post": {
        "tags": [ "account-tag" ],
        "operationId": "createAccount",
        "responses": {
          "200": {
            "description": "OK",
            "schema": { "$ref": "#/definitions/UserDTO" }
          }
        }
      }
    }
  }
}

编辑

池上的第二个建议果然奏效了。 这是我的最终解决方案

如果我们假设给定路径的所有方法( getpost等)共享相同的标签,我们可以简单地使用以下内容:

.paths |= with_entries( select( .value[].tags | index("account-tag") ) )

jqplay上的演示


如果该假设不成立,我们将需要在两个级别进行过滤。

.paths |= with_entries(
   .value |= with_entries(
      select( .value.tags | index("account-tag") )
   ) |
   select( .value | length > 0 )
)

jqplay上的演示

或者

.paths |= with_entries(
   .value = (
      .value |
      with_entries(
         select( .value.tags | index("account-tag") )
      ) |
      select( length > 0 )
   )
)

jqplay上的演示

(我讨厌我必须在这里使用.value = (.value |... )而不是.value |= (... ) 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM