I have some JSON that includes nested arrays for each thing I'm trying to collect.
I've distilled it here:
[
[
{
"Item":"FIRST",
"items":[
{
"firstitem1":"Item 1",
"firstitem2":"Item 2"
}
]
}
],
[
{
"Item":"SECOND",
"items":[
{
"seconditem1":"Second Item 1",
"seconditem2":"Second Item 2"
}
]
}
]
]
The desired output would look like:
{
"FirstItem1": "Item 1",
"SecondItem1": "Second Item 1"
}
I can return each item individually by using
.[0] | {FirstItem1: .[0].items[0].firstitem1}
.[1] | {seconditem: .[0].items[0].seconditem1}
I found a similar problem which explains that you can concatenate filters using something like filter + (filter) : Multiple filters using JQ
However, while both of my filters above work independantly, when I concatenate them in this way:
.[0] | {FirstItem1: .[0].items[0].firstitem1} + (.[1] | {seconditem: .[0].items[0].seconditem1})
I get 'null' for my second response.
{
"FirstItem1": "Item 1",
"seconditem": null
}
I've been scratching my head at this for a few days now, any ideas? I'd appreciate the nudge if I should attack this differently.
Here's a jqplay link https://jqplay.org/s/By94hv9gKj
I've been scratching my head at this for a few days now
You'll probably feel like pulling some hair out when you see how close you got. Basically, you just need an extra pair of parentheses:
(.[0] | {FirstItem1: .[0].items[0].firstitem1}) +
(.[1] | {seconditem: .[0].items[0].seconditem1})
Except you probably meant "SecondItem1" for the second key name.
Here's a less repetitive solution that might be worth considering:
[.[][] | .items[0]]
| {FirstItem1: first(.[0][]), SecondItem1: first(.[1][])}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With