簡體   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