Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

jq

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.
like image 678
San Avatar asked Jan 27 '15 06:01

San


People also ask

Does jq use JSONPath?

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.

What is jq JSON parser?

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.

Can jq write JSON?

jq is an amazing little command line utility for working with JSON data.


2 Answers

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

like image 178
Eric Hartford Avatar answered Sep 19 '22 00:09

Eric Hartford


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)' 
like image 45
abraham Avatar answered Sep 17 '22 00:09

abraham