首页 > 解决方案 > 使用 jq 在现有 JSON 中添加相同的数组元素

问题描述

我有一个 json 文件,我想在 json 的另一个位置从顶部添加一些值。我正在尝试使用 jq 命令行。

{
    "channel": "mychannel",
    "videos": [
        {
            "id": "10",
            "url": "youtube.com"
        },
        {
            "id": "20", 
            "url": "youtube.com"
        }
    ]
}

输出将是:

{
    "channel": "mychannel",
    "videos": [
        {
            "channel": "mychannel",
            "id": "10",
            "url": "youtube.com"
        },
        {
            "channel": "mychannel",
            "id": "20", 
            "url": "youtube.com"
        }
    ]
}

在我的 json 中,“通道”是静态的,总是相同的值。我需要一种在每个视频数组中始终连接的方法。

有人可以帮助我吗?

jq .videos + 频道

标签: jsonbashjq

解决方案


Use a variable to remember .channel in the later stages of the pipeline.

$ jq '.channel as $ch | .videos[].channel = $ch' tmp.json
{
  "channel": "mychannel",
  "videos": [
    {
      "id": "10",
      "url": "youtube.com",
      "channel": "mychannel"
    },
    {
      "id": "20",
      "url": "youtube.com",
      "channel": "mychannel"
    }
  ]
}

推荐阅读