如何用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 }
命令解析
to_entries[]:将外层对象转换为键值对数组,逐个处理每个外层键值对.key as $outer:保存当前外层键名到变量$outer,后续构造对象时使用.value:提取外层键对应的值,即包含内层未知键的对象to_entries[]:对内层对象重复键值对转换操作,逐个处理内层键值对.key as $inner:保存当前内层键名到变量$inner.value:提取内层键对应的值,包含otherProperties和items数组.items[] as $item:遍历items数组中的每个元素,保存到变量$item- 最后构造目标对象,整合
item、outer、inner和otherProperties四个字段
内容的提问来源于stack exchange,提问作者Goddy
相关产品推荐
相关产品推荐

