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

时间:2019-08-23 09:35:50

标签: json jq

我有一个只有一个对象的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"
}

仅在以下路径下,我需要将上述json文件值添加到以下json中 .paths.<any method that starts with />.get.parameters还没有该对象。 如果存在,则需要删除该对象,并需要添加上述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实现以上目标?

1 个答案:

答案 0 :(得分:2)

您几乎完全正确,但是缺少识别那些名称包含/的对象的部分。您可以在键名上使用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)