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

如何用jq清空dependencies对象所有键的值?命令错误修复

问题:使用jq清空JSON中dependencies对象的所有值

原始JSON数据:

json_string="$(cat <<<'END'
{
  "name": "hello",
  "dependencies": {
    "progress": "^2.0.0",
    "tar": "^6.2.1"
  }
}
END
)"

预期输出:

{
  "name": "hello",
  "dependencies": {
    "progress": "",
    "tar": ""
  }
}

你尝试的命令及错误输出:

output="$(jq ".dependencies =(.dependencies | keys)" <<< "$json_string")"
echo "output is: $output"

输出结果:

{
  "name": "hello",
  "dependencies": [
    "progress",
    "tar"
  ]
}

问题原因

你用的keys函数是把对象的键名提取成数组,所以会将dependencies从对象转换成键名数组,自然不符合保留对象结构的需求。

修复方案

有两种简单的jq命令可以实现需求:

方法1:直接遍历赋值

output="$(jq '.dependencies[] = ""' <<< "$json_string")"

这个命令直接对dependencies下的所有属性值赋值为空字符串,语法简洁直接。

方法2:用with_entries遍历键值对

output="$(jq '.dependencies |= with_entries(.value = "")' <<< "$json_string")"

with_entries会遍历对象的每个键值对({key:..., value:...}),这里指定把每个键值对的value设为空字符串,|=操作符表示把修改后的结果赋值回原属性。

运行任意一种命令后,输出都会符合你的预期:

{
  "name": "hello",
  "dependencies": {
    "progress": "",
    "tar": ""
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:21:14