使用 jq 连接 JSON 中的 2 个字段

Concat 2 fields in JSON using jq

我正在使用 jq 重新格式化我的 JSON

JSON 字符串:

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

想要的输出:

{"channel" : "profile_type.youtube"}

我的命令:

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

我知道下面的命令连接字符串。但它的工作逻辑与上述不同:

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

如何仅使用 jq 获得结果?

在字符串连接代码周围使用parentheses

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

这里有一个使用字符串插值的解决方案,正如 Jeff 建议的那样:

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

例如

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

字符串插值使用 \(foo) 语法(类似于 shell $(foo) 调用)。
见官方JQ manual.