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

如何用jq命令为内部列表添加根元素并转换JSON结构?

解决jq命令中上下文丢失导致字段为null的问题

问题分析

你的jq命令里,当通过.parent.innerList[]遍历数组元素时,当前上下文(.)已经切换为数组内的单个对象,此时再访问.parent就会因为找不到对应路径而返回null,这就是内部rootElement为空的原因。

正确命令

先将需要复用的rootElement值存入变量,遍历数组时直接引用该变量即可避免上下文问题:

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

示例输入

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

预期输出

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

补充说明

  • {id, value}是jq的语法糖,等价于{id: .id, value: .value},可以简化代码。
  • 通过变量$root缓存顶层的rootElement值,确保在数组遍历的子上下文中仍能访问到该值。

内容的提问来源于stack exchange,提问作者Justin J AR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:30:01