You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq将键值对对象转换为指定结构的数组

Answer

Absolutely! You can use jq's to_entries function to convert your key-value object into an array of structured entries, then reshape each entry to match your desired format.

Here's the jq command that gets the job done:

jq 'to_entries | map({key: .key} + .value)' input.json

How this works step-by-step:

  1. to_entries: This transforms your original object into an array of {key, value} pairs. For your input, this produces:
    [
      {
        "key": "alpha",
        "value": { "bytes": { "value": 4789440 }, "doc_count": 7723 }
      },
      {
        "key": "beta",
        "value": { "bytes": { "value": 4416862639 }, "doc_count": 1296 }
      }
    ]
    
  2. map({key: .key} + .value): For each entry in the array, we merge the key field with all properties from the value object. This combines them into the exact structure you requested.

Example Output:

Running the command on your input will output:

[
  {
    "key": "alpha",
    "bytes": { "value": 4789440 },
    "doc_count": 7723
  },
  {
    "key": "beta",
    "bytes": { "value": 4416862639 },
    "doc_count": 1296
  }
]

This method is flexible—it works for any number of top-level keys in your original object, not just "alpha" and "beta".

内容的提问来源于stack exchange,提问作者sontags

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:07:36