Reputation: 387
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
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