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

如何使用jq根据正则匹配键从另一字典更新对应JSON值

jq 实现方案

你可以使用以下命令完成需求,假设你的原始JSON A保存在a.json,用于更新的JSON B保存在b.json:

jq --slurpfile b b.json '. as $a | $b[0] | with_entries(select(.key | test("^[a-z]-$"))) | reduce to_entries[] as $e ($a; if has($e.key) then .[$e.key] = $e.value else . end)' a.json

命令逻辑说明

  • --slurpfile b b.json:将JSON B的内容读取到jq变量$b中,$b[0]即为JSON B的完整对象
  • with_entries(select(.key | test("^[a-z]-$"))):过滤出JSON B中键完全匹配[a-z]-规则的键值对,排除不符合规则的键
  • reduce to_entries[] as $e ($a; if has($e.key) then .[$e.key] = $e.value else . end):遍历过滤后的B的键值对,仅当JSON A中存在同名键时才执行更新,不存在的键直接跳过,不会新增到JSON A中

直接测试命令

如果你不想新建文件,可以直接用管道传入两个JSON内容测试效果:

echo '{"a-":{"v":1},"b-":{"v":2},"c":{"v":3}}' | jq --slurpfile b <(echo '{"a-":{"v":9},"b-":{"v":9},"d":{"v":9}}') '. as $a | $b[0] | with_entries(select(.key | test("^[a-z]-$"))) | reduce to_entries[] as $e ($a; if has($e.key) then .[$e.key] = $e.value else . end)'

运行后将直接输出你预期的更新结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:48:01