简体   繁体   English

使用JQ向键数组添加值

[英]add values to array of keys with JQ

I have a simple JSON array: 我有一个简单的JSON数组:

[
"smoke-tests",
"other-tests"
]

I'd like to convert to a simple JSON: 我想转换为简单的JSON:

{"smoke-tests": true,
 "other-tests": true
}

I've tried several jq examples, but none seem to do what I want. 我已经尝试了几个jq示例,但是似乎没有一个可以满足我的要求。

jq '.[] | walk(.key = true)' jq '.[] | walk(.key = true)' produces a compile error. jq '.[] | walk(.key = true)'会产生编译错误。

$ s='["smoke-tests", "other-tests"]'
$ jq '[.[] | {(.): true}] | add' <<<"$s"
{
  "smoke-tests": true,
  "other-tests": true
}

Breaking down how that works: .[] | {(.): true} 分解其工作方式: .[] | {(.): true} .[] | {(.): true} converts each item into a dictionary mapping the value (as a key) to true . .[] | {(.): true}将每个项目转换为将值(作为键)映射为true的字典。 Surrounding that in [ ] means we generate a list of such objects; [ ]中将其[ ]意味着我们生成了此类对象的列表; sending that to add combines them into a single object. 发送add将它们组合为一个对象。

如果您喜欢reduce的效率,但是不想显式地使用reduce

. as $in | {} | .[$in[]] = true

Here is a solution using add. 这是使用添加的解决方案。 It's close to Charles 's solution but uses the behavior of Object construction to implicitly return multiple objects when used with an expression which returns multiple results. 它与Charles的解决方案很接近,但是当与返回多个结果的表达式一起使用时,使用Object构造的行为隐式返回多个对象。

 [{(.[]):true}]|add

With reduce() function: 使用reduce()函数:

jq 'reduce .[] as $k ({}; .[$k]=true)' file

The output: 输出:

{
  "smoke-tests": true,
  "other-tests": true
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM