Concat 2 fields in JSON using jq

隐身守侯 提交于 2020-05-24 16:44:09

问题


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?


回答1:


Use parentheses around the string concatenation code:

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



回答2:


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.



来源:https://stackoverflow.com/questions/37710718/concat-2-fields-in-json-using-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!