I have a json file with just one object as below. Am calling it 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"
}
I need to add the above json file value into the below json, only if the below path .paths.<any method that starts with />.get.parameters
does not have that object already. If it exists that object needs to be removed and the contents of the above Auth.json needs to be added. I have jq 1.5 and do have access on the system to update the jq initialization file, so could not use walk function which would've made this simpler.
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"
}
]
}
}
}
}
I tried the below command, but it is adding it recursively within all objects of the path in the Main.json.
jq --slurpfile newval Auth.json '.paths | .. | .get.parameters += $newval' Main.json > test.json
How can I achieve the above using jq 1.5?
You got it almost right, but missing the part to identify those objects whose name contains /
. You can use startswith()
on the keyname
jq --slurpfile auth Auth.json '
.paths |= with_entries(
if .key|startswith("/")
then
.value.get.parameters |= $auth
else
. end
)' Main.json
Additionally, if you would like to compare if .parameters
object does not already contain the Authentication object, change your if condition to
if (.key|startswith("/")) and (.value.get.parameters[] != $auth)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.