martin66
martin66

Reputation: 387

Using jq how to add the key to the existing JSON data structure

Hello and thanks in advance,

So I have the following JSON:

{
  "key1" : { 
     "someKey": "someValue"
  },
  "key2" : { 
     "someKey": "someValue"
  }
}

and the output that I'm looking for is:

[
  { 
     "someKey": "someValue",
     "$key" : "key1"
  },
  { 
     "someKey": "someValue",
     "$key" : "key2"
  }
]

So basically I need to append the 'key' to the value as a separate property in the value of that key's object using jq.

I already figured out how to convert the values into an array, but I cannot figure out how to add the "$key" to the object.

Please help. Thanks.

Upvotes: 1

Views: 599

Answers (1)

martin66
martin66

Reputation: 387

I found the solution using the following command:

[ to_entries[] | {"$key": .key} * .value ]

How this works?

The to_entries[] outputs

{
 "key": "key1",
  "value": {
    "someKey": "someValue"
  }
}
{
  "key": "key2",
  "value": {
    "someKey": "someValue"
  }
}

Then it pipes this output using '|', after piping it creates an object

{"$key": .key}

Then, using the * operator, it merges this new object with the object located at the .value key from each object from the to_entries[] output.

The outermost wrapping with [] just creates an array from the stream.

Upvotes: 4

Related Questions