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

如何使用jq行内编辑JSON文件,实现字段修改与键值增删

使用jq完成JSON的指定修改与行内编辑

原始JSON内容:

{
"arrays": [
    {
      "name": "foo",
      "properties": [
        {
          "type": "app",
          "url": "https://example.com",
          "checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"
        }
      ]
    }
  ]
}

目标效果:修改type值为"Bar",删除url和checksum字段,新增file字段并赋值为"filename",最终得到:

{
"arrays": [
    {
      "name": "foo",
      "properties": [
        {
          "type": "Bar",
          "file": "filename"
        }
      ]
    }
  ]
}

完整jq修改命令

你可以用以下命令一次性完成所有修改:

jq '(.arrays[] | select(.name == "foo").properties[]) |= ({type: "Bar", file: "filename"})' test.json

命令说明

  • (.arrays[] | select(.name == "foo").properties[]):精准定位到arrays数组中name为foo的对象下的properties数组元素
  • |= ({type: "Bar", file: "filename"}):将定位到的对象直接替换为包含指定字段的新对象,自动移除原有的url和checksum,同时完成type修改与file新增

行内编辑实现

jq本身没有原生行内编辑功能,要直接修改原文件可采用以下两种方式:

方法1:使用临时文件中转

jq '(.arrays[] | select(.name == "foo").properties[]) |= ({type: "Bar", file: "filename"})' test.json > temp.json && mv temp.json test.json

方法2:使用sponge工具(需先安装moreutils包)

sponge可读取标准输入并写入目标文件,无需手动处理临时文件:

jq '(.arrays[] | select(.name == "foo").properties[]) |= ({type: "Bar", file: "filename"})' test.json | sponge test.json

内容的提问来源于stack exchange,提问作者user22990699

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:42:33