Concat 2 fields in JSON using jq

JsonJq

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

Use parentheses around the string concatenation code:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' \
 | jq '{channel: (.profile_type + "." + .channel)}'

Solution 2 - Json

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondarthsidiousView Question on Stackoverflow
Solution 1 - JsonAnthony BattagliaView Answer on Stackoverflow
Solution 2 - Jsonjq170727View Answer on Stackoverflow