Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested arrays, combining multiple filters using JQ

Tags:

json

filter

jq

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

like image 618
detonationbox0 Avatar asked Mar 07 '26 05:03

detonationbox0


1 Answers

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.

An alternative

Here's a less repetitive solution that might be worth considering:

[.[][] | .items[0]]
| {FirstItem1: first(.[0][]), SecondItem1: first(.[1][])}
like image 94
peak Avatar answered Mar 10 '26 15:03

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!