149

I am using jq to reformat my JSON.

JSON String:

{"channel": "youtube", "profile_type": "video", "member_key": "hello"}

Wanted output:

{"channel" : "profile_type.youtube"}

My command:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' | jq -c '. | {channel: .profile_type + "." + .member_key}'

I know that the command below concatenates the string. But it is not working in the same logic as above:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' | jq -c '.profile_type + "." + .member_key'

How can I achieve my result using ONLY jq?

eel ghEEz
  • 1,186
  • 11
  • 24
darthsidious
  • 2,851
  • 3
  • 19
  • 30

2 Answers2

189

Use parentheses around the string concatenation code:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' \
 | jq '{channel: (.profile_type + "." + .channel)}'
thanasisp
  • 5,855
  • 3
  • 14
  • 31
Anthony Battaglia
  • 2,499
  • 1
  • 12
  • 8
86

Here is a solution that uses string interpolation as Jeff suggested:

{channel: "\(.profile_type).\(.member_key)"}

e.g.

$ jq '{channel: "\(.profile_type).\(.member_key)"}' <<EOF
> {"channel": "youtube", "profile_type": "video", "member_key": "hello"}
> EOF
{
  "channel": "video.hello"
}

String interpolation works with the \(foo) syntax (which is similar to a shell $(foo) call).
See the official JQ manual.

Benoit Duffez
  • 11,839
  • 12
  • 77
  • 125
jq170727
  • 13,159
  • 3
  • 46
  • 56