Json – Using jq to parse and display multiple fields in a json serially

jqjson

I have this Json

{
    "users": [
        {
            "first": "Stevie",
            "last": "Wonder"
        },
        {
            "first": "Michael",
            "last": "Jackson"
        }
    ]
}

Using jq I'd like to display first and last name serially. Like so –

Stevie Wonder
Michael Jackson

This is how far I have gotten –

jq '.users[].first, .users[].last'

But it displays

"Stevie"
"Michael"
"Wonder"
"Jackson"

Notice the following:

  1. The double quotes that I do not want.
  2. The carriage return that I do not want.
  3. It's jumbled up. My query displays all the first names first, and then all the last names. However, I want first-last, first-last pair.

Best Answer

I recommend using String Interpolation:

jq '.users[] | "\(.first) \(.last)"'

We are piping down the result of .users[] to generate the string ".first .last" using string interpolation. \(foo) syntax is used for string interpolation in jq. So, for the above example, it becomes "Stevie Wonder" (".users[].first .users[].second" working elementwise) and "Michael Jackson".

jq reference: String interpolation

Related Question