如何在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
相关产品推荐
相关产品推荐

