user766353
user766353

Reputation: 537

How do I create a jq query that extracts data from 2 separate levels of a JSON file?

I have a JSON file that looks something like this:

{
    "people": {
        "company": "Acme",
        "department": "Dev",
        "perks": {
            "eat": "pizza",
            "drink": "beer",
            "play": "twister"
        },
        "names": [{
                "last_name": "Smith",
                "first_names": [{
                        "name": "Bill"
                    },
                    {
                        "name": "Alice"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Brown",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Bob"
                    },
                    {
                        "name": "Mary"
                    }
                ]
            },
            {
                "last_name": "Sanchez",
                "first_names": [{
                        "name": "Gil"
                    },
                    {
                        "name": "Jose"
                    },
                    {
                        "name": "Marlena"
                    }
                ]
            }
        ]
    }
}

The output I'm looking for is:

acme
Dev
twister
Smith, Bill
Smith, Alice
Smith, Mary
Brown, Gil
Brown, Bob
Brown, Mary
Sanchez, Gil
Sanchez, Jose
Sanchez, Marlena

I have the jq query that gets the names:

jq -r '.people | .names[] | "\(.last_name), \(.first_names[].name)"'

And I have the query that gets me the first 3 lines (Acme, Dev, twister):

jq -r '.people | .company, .department, .perks.play'

But when I try to combine them (in too many ways to list here!), I get an error. I don't know how to combine these to get the query to walk the first level below ".people" and then the level below ".people.names[]" (all in one query).

Upvotes: 0

Views: 63

Answers (1)

peak
peak

Reputation: 116740

Simply use the "," operator to join the two queries, e.g.

.people
| (.company, .department, .perks.play),
  (.names[] | "\(.last_name), \(.first_names[].name)")

Upvotes: 1

Related Questions