如何使用jq更新数组中的多个对象

时间:2019-01-05 10:17:42

标签: arrays json edit jq

使用jq我想有条件地更新"folders"数组中的对象。 对于每个包含"cand_name":"folderA"的对象,应添加一个值为"files"的新属性compare.files

{
  "tmp":{
    "folders":[
      {
        "ref_name":"folderB",
        "cand_name":"folderA"
      },
      {
        "ref_name":"folderC",
        "cand_name":"folderA"
      },
      {
        "ref_name":"folderC",
        "cand_name":"folderE"
      }
    ],
    "compare":{
      "files":[
        {
          "candidate":"Z3S1"
        }
      ]
    }
  }
}

对于上述输入,预期输出应为

{
  "tmp":{
    "folders":[
      {
        "ref_name":"folderB",
        "cand_name":"folderA"
        "files":[
          {
            "candidate":"Z3S1"
          }
        ]
      },
      {
        "ref_name":"folderC",
        "cand_name":"folderA"
        "files":[
          {
            "candidate":"Z3S1"
          }
        ]
      },
      {
        "ref_name":"folderC",
        "cand_name":"folderE"
      }
    ],
    "compare":{
      "files":[
        {
          "candidate":"Z3S1"
        }
      ]
    }
  }
 }

1 个答案:

答案 0 :(得分:0)

简单解决方案的关键是|=。使用预期的输出作为预期要求的指南,可以编写:

.tmp.compare.files as $f
| .tmp.folders 
  |= map( if .cand_name=="folderA" 
          then .files = $f else . end)