【问题标题】:add values to array of keys with JQ使用 JQ 向键数组添加值
【发布时间】:2017-09-22 19:59:35
【问题描述】:

我有一个简单的 JSON 数组:

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

我想转换成简单的 JSON:

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

我已经尝试了几个 jq 示例,但似乎没有一个符合我的要求。

jq '.[] | walk(.key = true)' 产生编译错误。

【问题讨论】:

    标签: json object key jq


    【解决方案1】:

    如果你喜欢reduce 的效率但又不想明确使用reduce

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

    【讨论】:

    • 谢谢,@peak;优雅而简单。
    【解决方案2】:
    $ s='["smoke-tests", "other-tests"]'
    $ jq '[.[] | {(.): true}] | add' <<<"$s"
    {
      "smoke-tests": true,
      "other-tests": true
    }
    

    分解其工作原理:.[] | {(.): true} 将每个项目转换为将值(作为键)映射到 true 的字典。在[ ] 中包围它意味着我们生成一个此类对象的列表;将其发送到add 会将它们组合成一个对象。

    【讨论】:

      【解决方案3】:

      这是一个使用 add 的解决方案。它接近Charles 的解决方案,但使用Object construction 的行为在与返回多个结果的表达式一起使用时隐式返回多个对象。

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

      【讨论】:

        【解决方案4】:

        带有reduce()功能:

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

        输出:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-06-12
          • 2022-12-06
          • 2022-01-13
          • 1970-01-01
          • 1970-01-01
          • 2017-07-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多