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

如何用JQ 1.6展开键名未知的双层嵌套JSON对象?

解决双层未知键名嵌套JSON的展开问题

原始JSON结构

{
    "outerDescription1": {
        "innerDescription1": {
            "otherProperties": 1,
            "items": [
                "arrayItem1",
                "arrayItem2"
            ]
        }
    },
    "outerDescription2": {
        "innerDescription2": {
            "otherProperties": 2,
            "items": [
                "arrayItem3",
                "arrayItem4"
            ]
        }
    }
}

期望输出结果

{
    "item": "arrayItem1",
    "outer": "outerDescription1",
    "inner": "innerDescription1",
    "otherProperties": 1
}
{
    "item": "arrayItem2",
    "outer": "outerDescription1",
    "inner": "innerDescription1",
    "otherProperties": 1
}
{
    "item": "arrayItem3",
    "outer": "outerDescription2",
    "inner": "innerDescription2",
    "otherProperties": 2
}
{
    "item": "arrayItem4",
    "outer": "outerDescription2",
    "inner": "innerDescription2",
    "otherProperties": 2
}

尝试过的命令及中间结果

使用以下JQ命令:

with_entries(.value = {outer: .key} + .value)[]

得到的中间结果:

{                              
  "outer": "outerDescription1",
  "innerDescription1": {        
    "otherProperties": 1,       
    "items": [                  
      "arrayItem1",             
      "arrayItem2"               
    ]                          
  }                            
}                              
{                              
  "outer": "outerDescription2",
  "innerDescription2": {        
    "otherProperties": 2,       
    "items": [                  
      "arrayItem3",             
      "arrayItem4"               
    ]                          
  }                            
}   

解决方案

针对未知名称的外层和内层键,可以通过两次遍历键值对的方式展开,使用以下JQ 1.6兼容的命令:

to_entries[]
| .key as $outer
| .value
| to_entries[]
| .key as $inner
| .value
| .items[] as $item
| {
    item: $item,
    outer: $outer,
    inner: $inner,
    otherProperties: .otherProperties
  }

命令解析

  1. to_entries[]:将外层对象转换为键值对数组,逐个处理每个外层键值对
  2. .key as $outer:保存当前外层键名到变量$outer,后续构造对象时使用
  3. .value:提取外层键对应的值,即包含内层未知键的对象
  4. to_entries[]:对内层对象重复键值对转换操作,逐个处理内层键值对
  5. .key as $inner:保存当前内层键名到变量$inner
  6. .value:提取内层键对应的值,包含otherProperties和items数组
  7. .items[] as $item:遍历items数组中的每个元素,保存到变量$item
  8. 最后构造目标对象,整合item、outer、inner和otherProperties四个字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:50:38