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:
JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.
jq is a command-line tool for parsing JSON. Most of the popular API and data services use the JSON data format, so we'll learn how it's used to serialize interesting information, and how to use the jq to parse it at the command-line.
jq is an amazing little command line utility for working with JSON data.
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
You can use addition to concatenate strings.
Strings are added by being joined into a larger string.
jq '.users[] | .first + " " + .last'
The above works when both first
and last
are string. If you are extracting different datatypes(number and string), then we need to convert to equivalent types. Referring to solution on this question. For example.
jq '.users[] | .first + " " + (.number|tostring)'
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