【发布时间】:2017-09-22 19:59:35
【问题描述】:
我有一个简单的 JSON 数组:
[
"smoke-tests",
"other-tests"
]
我想转换成简单的 JSON:
{"smoke-tests": true,
"other-tests": true
}
我已经尝试了几个 jq 示例,但似乎没有一个符合我的要求。
jq '.[] | walk(.key = true)' 产生编译错误。
【问题讨论】:
我有一个简单的 JSON 数组:
[
"smoke-tests",
"other-tests"
]
我想转换成简单的 JSON:
{"smoke-tests": true,
"other-tests": true
}
我已经尝试了几个 jq 示例,但似乎没有一个符合我的要求。
jq '.[] | walk(.key = true)' 产生编译错误。
【问题讨论】:
如果你喜欢reduce 的效率但又不想明确使用reduce:
. as $in | {} | .[$in[]] = true
【讨论】:
$ s='["smoke-tests", "other-tests"]'
$ jq '[.[] | {(.): true}] | add' <<<"$s"
{
"smoke-tests": true,
"other-tests": true
}
分解其工作原理:.[] | {(.): true} 将每个项目转换为将值(作为键)映射到 true 的字典。在[ ] 中包围它意味着我们生成一个此类对象的列表;将其发送到add 会将它们组合成一个对象。
【讨论】:
这是一个使用 add 的解决方案。它接近Charles 的解决方案,但使用Object construction 的行为在与返回多个结果的表达式一起使用时隐式返回多个对象。
[{(.[]):true}]|add
【讨论】:
带有reduce()功能:
jq 'reduce .[] as $k ({}; .[$k]=true)' file
输出:
{
"smoke-tests": true,
"other-tests": true
}
【讨论】: