5

I'd like to print with JQ arbitrary composed strings.

Suppose I have a json document* as follow:

[{
  "first_name": "Angela",
  "last_name": "Sleney",
  "email": "asleney0@nytimes.com"
}, {
  "first_name": "Clint",
  "last_name": "Ducroe",
  "email": "cducroe1@aboutads.info"
}, {
  "first_name": "Aurthur",
  "last_name": "Tebb",
  "email": "atebb2@fastcompany.com"
}]

and with data from above let's say just for example (could be any string) I'd like to print with JQ 3 lines as follow:

Email address for user Angela Sleney is "asleney0@nytimes.com"
Email address for user Clint Ducroe is "cducroe1@aboutads.info"
Email address for user Aurthur Tebb is "atebb2@fastcompany.com"

How can I do this?


Best I was able to do was to print the data 1 per line with:

jq -r '.[] | .first_name, .last_name, .email, ""'

But result was

Angela
Sleney
asleney0@nytimes.com

Clint
Ducroe
cducroe1@aboutads.info

Aurthur
Tebb
atebb2@fastcompany.com

*NB: the data comes from random generator, no real names or emails.

peak
  • 105,803
  • 17
  • 152
  • 177
Gruber
  • 2,196
  • 5
  • 28
  • 50

2 Answers2

9

I tried playing around with your json on jqplay.

I got the desired result -

Email address for user Angela Sleney is "asleney0@nytimes.com"
Email address for user Clint Ducroe is "cducroe1@aboutads.info"
Email address for user Aurthur Tebb is "atebb2@fastcompany.com"

with this filter -

.[] | "Email address for user \(.first_name) \(.last_name) is \"\(.email)\""

Play around with the string interpolation \(foo) to get your result.

Gruber
  • 2,196
  • 5
  • 28
  • 50
Rohit Mishra
  • 151
  • 5
  • 1
    The way you have the single quotes written isn't necessary, you could use them as is: `'\(.email)'` though double quotes seem to be preferred: `\"\(.email)\"` – Jeff Mercado Jan 01 '20 at 09:37
  • I knew it I was missing a simple feature, I was very surprised that a common request as mine wasn't addressed somehow by the program. RTFM strikes back, totally missed it in the documentation. Thank you! – Gruber Jan 01 '20 at 21:29
0

Try this:

jq -r '.[] | .first_name + " " + .last_name + " " + .email'

Addition: +

The operator + takes two filters:

  • Applies them both to the same input
  • Adds the results together.

The term “adding” here has a different meaning depending on the types involved:

  • Numbers are added by normal arithmetic.
  • Arrays are added by concatenating each other forming a larger array.
  • Strings are added by appending one with another to form a larger string.

Refer here for more details:

Source: https://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions

Community
  • 1
  • 1