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

如何在jq的sub函数中使用JSON元素而非字面量?

jq使用JSON元素作为sub函数参数的解决办法

问题重现

给定示例JSON:

{
    "example": {
        "search_for": "https://a-url-using-a-shortener.com",
        "replace_with": "https://my.site.com",
        "text": "I want to have the full URL, not https://a-url-using-a-shortener.com" 
    }
}

用字面量作为sub参数的命令可正常执行:

.example | .text | sub("https://a-url-using-a-shortener.com";"https://my.site.com")

得到预期输出:

"I want to have the full URL, not https://my.site.com"

但改用JSON字段作为参数时:

.example | .text | sub( .search_for ; .replace_with )

触发报错:

jq: error (at /dev/stdin:6): Cannot index string with string "search_for"

问题根源

执行.example | .text后,当前处理的对象已经变成字符串类型的文本内容,此时再尝试访问.search_for字段,自然会报错——字符串无法被索引提取子字段。

两种可行解法

解法1:提前保存参数到变量

先把search_for和replace_with的值存入变量,再对.text执行替换:

.example | .search_for as $search | .replace_with as $replace | .text | sub($search; $replace)

解法2:在父上下文直接操作

保持上下文在.example对象层级,直接对.text字段执行替换操作:

  • 仅输出修改后的文本:
.example | (.text | sub(.search_for; .replace_with))
  • 修改原JSON中的.text字段并输出完整结构:
.example | .text |= sub(.search_for; .replace_with)

验证结果

执行上述正确命令后,均可得到预期结果:

"I want to have the full URL, not https://my.site.com"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:26:04