Gruber
Gruber

Reputation: 2298

How can I print an arbitrary string with JQ?

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": "[email protected]"
}, {
  "first_name": "Clint",
  "last_name": "Ducroe",
  "email": "[email protected]"
}, {
  "first_name": "Aurthur",
  "last_name": "Tebb",
  "email": "[email protected]"
}]

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 "[email protected]"
Email address for user Clint Ducroe is "[email protected]"
Email address for user Aurthur Tebb is "[email protected]"

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
[email protected]

Clint
Ducroe
[email protected]

Aurthur
Tebb
[email protected]

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

Upvotes: 6

Views: 3470

Answers (2)

John Marcou
John Marcou

Reputation: 1

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

Upvotes: 0

Rohit Mishra
Rohit Mishra

Reputation: 151

I tried playing around with your json on jqplay.

I got the desired result -

Email address for user Angela Sleney is "[email protected]"
Email address for user Clint Ducroe is "[email protected]"
Email address for user Aurthur Tebb is "[email protected]"

with this filter -

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

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

Upvotes: 9

Related Questions