Reputation: 499
Sample input.json
[{
"organizationId": "org1",
"runtimeVersion": "3545",
"type": "rest-api",
"server": "test1",
"status": "UP"
}]
Expected output.json
[{
"organizationId": "org1",
"runtimeVersion": "3545",
"type": "rest-api",
"server": "test1",
"status": "UP",
"test1": "UP"
}]
The input is an array object. I need to add new key which is the value of key server. The value of this new key should value of the key status.
Any solutions on achieving this using jq
Upvotes: 1
Views: 255
Reputation: 116740
In the spirit of Polya's "How to Solve It", let's start by observing that the fact that the object to be updated is in an array is a distraction, so let's focus on the task at hand:
adding a key-value pair to a JSON object
"Add" is thus a helpful word to keep in mind, and indeed looking at the jq manual, you will find both "+" and "add". If . is the starting object, then we could achieve the update by writing:
. + {(.server): .status}
(The parentheses around .server
are necessary as .server
has to be evaluated.)
The above expression is a filter, and the usual way of applying a filter to each member of an array is using map
. This leads to what might be the most "elementary" (as in "my dear Watson") solution to the problem:
map(. + {(.server): .status})
Another approach would be to use the "assignment syntax" to add (or modify) a key, leading to an even shorter solution:
map( .[.server] = .status )
Maybe that is no less elementary ...
Upvotes: 1
Reputation: 92854
Simple jq
approach:
jq '.[] |= . + {(.server):.status}' file.json
The output:
[
{
"organizationId": "org1",
"runtimeVersion": "3545",
"type": "rest-api",
"server": "test1",
"status": "UP",
"test1": "UP"
}
]
Upvotes: 1