1

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

Naveen K Reddy
  • 429
  • 5
  • 13

2 Answers2

1

Simple jq approach:

jq '.[] |= . + {(.server):.status}' file.json

The output:

[
  {
    "organizationId": "org1",
    "runtimeVersion": "3545",
    "type": "rest-api",
    "server": "test1",
    "status": "UP",
    "test1": "UP"
  }
]
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

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 ...

peak
  • 105,803
  • 17
  • 152
  • 177
  • The best explanation! Perfectly understood. Thank you so much for your time for explaining it to us! – Naveen K Reddy Mar 30 '18 at 21:32
  • One thing though.Can you please explain the difference between [.server] and (.server) and the simple use cases? I have seen (.server) evaluates it but confused with [.server] at the end of your post? – Naveen K Reddy Mar 30 '18 at 21:44
  • @NaveenKReddy - I'd suggest consulting the materials mentioned at https://github.com/stedolan/jq/wiki/FAQ#tutorials – peak Mar 30 '18 at 22:12
  • can you please check https://stackoverflow.com/questions/49586355/how-to-compare-one-field-that-is-common-in-each-object-of-an-array-in-two-files – Naveen K Reddy Mar 31 '18 at 09:41
  • can you please check https://stackoverflow.com/questions/49800086/jq-retain-missing-array-objects-from-capturing-group-and-update-array – Naveen K Reddy Apr 12 '18 at 15:11