Will Pittman
Will Pittman

Reputation: 1

jq filtering sub-array values with main values of an object

I am having an issue figuring out what filters and methods I need to use in jq to transform my json data into what I am looking for. Every combination I have tried has ended up either not working at all, or iterating for each value, for each sub-arrary, for each object.

I have spent too long on this and am not making any more progress. Need someone to put another set of eyes on it. I am sure it is something more simple than I am making it out to be, but I am just unable to figure it out!

Here is the json data I am working with:

[
    {
        "location": "locationa",
        "services": [
            {
                "name": "serviceA",
                "version": "5.2.0.2",
                "updatedAt": "2018-04-17"
            },
            {
                "name": "serviceB",
                "version": "4.19.0.5",
                "updatedAt": "2018-04-17"
            }
        ]
    },
    {
        "location": "locationb",
        "services": [
            {
                "name": "serviceA",
                "version": "5.2.0.2",
                "updatedAt": "2018-04-17"
            },
            {
                "name": "serviceB",
                "version": "4.19.0.5",
                "updatedAt": "2018-04-17"
            },
            {
                "name": "serviceC",
                "version": "1.0.0.1",
                "updatedAt": "2018-04-17"
            }
        ]
    }
]

And this is the format I am attempting to get out:

locationa serviceA 5.2.0.2
locationa serviceB 4.19.0.5
locationb serviceA 5.2.0.2
locationb serviceB 4.19.0.5
locationb serviceC 1.0.0.1

Upvotes: 0

Views: 1608

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134611

Generally when trying to output csv/tsv, you would want to generate arrays of the rows to output then pass to the @csv or @tsv or utilize join/1 to output in the format of your choice.

jq -r '.[] | [.location] + (.services[] | [.name, .version]) | @tsv' input.json

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50815

you can concatenate strings using + operator:

jq -r '.[]|.location+" "+(.services[]|.name+" "+.version)' file
locationa serviceA 5.2.0.2
locationa serviceB 4.19.0.5
locationb serviceA 5.2.0.2
locationb serviceB 4.19.0.5
locationb serviceC 1.0.0.1

Upvotes: 1

Related Questions