【问题标题】:Concat 2 fields in JSON using jq使用 jq 在 JSON 中连接 2 个字段
【发布时间】:2016-10-09 04:57:50
【问题描述】:

我正在使用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 来实现我的结果?

【问题讨论】:

  • 我想我正在尝试用我的 youtube API 脚本做同样的事情;)

标签: json jq


【解决方案1】:

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

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

【讨论】:

  • 考虑使用字符串插值代替,比多个字符串连接更简洁。
【解决方案2】:

这是一个使用字符串插值作为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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    相关资源
    最近更新 更多