繁体   English   中英

有条件地将json文件添加到jq 1.5中的Main json文件中

[英]Conditionally add json file into Main json file in jq 1.5

我有一个只有一个对象的json文件,如下所示。 我称它为Auth.json

{ 
    "name": "Authorization",
    "description": "This parameter represents the Authorization token obtained from the OKTA Authorization server. It is the Bearer token provided to authorize the consumer. Usage Authorization : Bearer token",
     "in": "header",
     "required": true,
     "type": "string"
}

仅当以下路径.paths.<any method that starts with />.get.parameters都没有该对象.paths.<any method that starts with />.get.parameters我才需要将上述json文件值添加到以下json中。 如果存在,则需要删除该对象,并需要添加上述Auth.json的内容。 我有jq 1.5,并且可以访问系统来更新jq初始化文件,因此无法使用walk函数,这会使此过程变得更加简单。

Main.json

{
  "swagger": "2.0",
    "paths": {
    "/agents/delta": {
      "get": {
        "description": "lorem ipsum doram",
        "operationId": "getagentdelta",
        "summary": "GetAgentDelta",
        "tags": [
          "Agents"
        ],
        "parameters": [
          {
            "name": "since",
            "in": "query",
            "description": "Format - date-time (as date-time in RFC3339). The time from which you need changes from. You should use the format emitted by Date's toJSON method (for example, 2017-04-23T18:25:43.511Z). If a timestamp older than a week is passed, a business rule violation will be thrown which will require the client to change the from date. As a best-practice, for a subsequent call to this method, send the timestamp when you <b>started</b> the previous delta call (instead of when you completed processing the response or the max of the lastUpdateOn timestamps of the returned records). This will ensure that you do not miss any changes that occurred while you are processing the response from this method",
            "required": true,
            "type": "string"
          }
        ]
        }
        }
        }
        }

我尝试了以下命令,但它是在Main.json中路径的所有对象中递归添加的。

jq --slurpfile newval Auth.json '.paths | .. | .get.parameters += $newval' Main.json > test.json

如何使用jq 1.5实现以上目标?

您几乎可以理解,但是缺少识别那些名称包含/对象的部分。 您可以在键名上使用startswith()

jq --slurpfile auth Auth.json '
    .paths |= with_entries( 
        if .key|startswith("/") 
        then
           .value.get.parameters |= $auth  
        else 
           . end
    )' Main.json

此外,如果您想比较.parameters对象是否尚未包含Authentication对象,请将if条件更改为

if (.key|startswith("/")) and (.value.get.parameters[] != $auth)

暂无
暂无

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

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