jq - 使用 Jq 在另一个属性中插入对象的属性

我有一个看起来像这样的 json 文件:

[
  {
    "account_id": 123, 
    "instances": [
      {"id": 1},
      {"id": 2}
    ]
  },
  {
    "account_id": 456, 
    "instances": [
      {"id": 1}
    ]
  }
]

我想将实例展平到一个列表中,并将 account_id 插入每个实例中。这是我想要的结果。

[
  {"id": 1, "account_id": 123},
  {"id": 2, "account_id": 123},
  {"id": 1, "account_id": 456}
]

这是我在等待答案时提出的替代解决方案。

jq '.|map(.instances[]+{"account_id": .account_id})' file.json

回答1

jq '[.[] | .id = .instances[0].id | del(.instances)]' file.json

如果有更多实例,只需遍历所有实例以将 account_id 分配给每个实例:

jq '[.[] | .id = .instances[].id | del(.instances)]' file.json
                           ~~

相似文章

随机推荐

最新文章