jq 命令用于获取内部列表中的根元素

问题描述 投票:0回答:1

这是我的示例 json

{
  "parent": {
    "rootElement": "root",
    "innerList": [
      {"id": 1, "value": "A"},
      {"id": 2, "value": "B"},
      {"id": 3, "value": "C"}
    ]
  }
}

我想要一个像这样使用 jq 命令转换的 json

{"innerList": [
        {"id": 1, "rootElement": "root", "value": "A"
        },
        {"id": 2, "rootElement": "root", "value": "B"
        },
        {"id": 3, "rootElement": "root", "value": "C"
        }
    ],
 "rootElement": "root"
}

我尝试了这个命令,但我没有得到所需的输出,因为一旦我解析内部列表,我就无法访问根元素。

jq '{rootElement: .parent.rootElement, innerList: [.parent.innerList[] | {id, value: .value, rootElement: .parent.rootElement}]}'

我明白了

{"innerList": [
        {"id": 1, "rootElement": null, "value": "A"
        },
        {"id": 2, "rootElement": null, "value": "B"
        },
        {"id": 3, "rootElement": null, "value": "C"
        }
    ],
 "rootElement": "root"
}
jq
1个回答
0
投票

rootElement
的迭代之外访问
.innerList[]

.parent | .innerList[] += {rootElement}
{
  "rootElement": "root",
  "innerList": [
    {
      "id": 1,
      "value": "A",
      "rootElement": "root"
    },
    {
      "id": 2,
      "value": "B",
      "rootElement": "root"
    },
    {
      "id": 3,
      "value": "C",
      "rootElement": "root"
    }
  ]
}

演示

© www.soinside.com 2019 - 2024. All rights reserved.