【问题标题】:jq not writing value of variable but the actual text of the variable namejq不是写变量的值而是变量名的实际文本
【发布时间】:2021-11-11 15:05:11
【问题描述】:

我正在用 bash 编写脚本来编辑一个 json 模板,用我的脚本的参数替换一些字段值,并尝试使用 jq 进行编辑。我的代码不是将 --arg 替换为参数的值,而是参数名称的文字文本。

我的模板包含:

{
"name":""
}

我的jq码:

jq --arg ad "192.168.5.5" -r '.name = "Addr $ad"' address.tmpl

这个输出:

{
    "name": "Addr $ad"
}

或者,如果我删除双引号

jq --arg ad "192.168.5.5" -r '.name = Addr $ad' address.tmpl

我明白了

jq: error: syntax error, unexpected '$', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.name = Addr $ad
jq: 1 compile error

根据我所阅读的所有内容,这应该可以。我在做什么错/我该如何解决这个问题????

操作系统 = Debian 10

【问题讨论】:

    标签: json bash jq


    【解决方案1】:
    jq --arg ad 192.168.5.5 -r '.name = "Addr " + $ad' address.tmpl
    

    $ad 如果不是硬引用,将由 shell 扩展。在jq 中,您可以使用字符串插值"Addr \($ad)" 或连接(如上),我觉得这更易读。

    【讨论】:

    • @ikegami 是的,我想“不得引用”并不是描述它的最准确方式。相应地进行了编辑。我发现 + 语法在这里更易读。
    • @ikegami 感谢您的建议。我考虑了一些清理工作并这样做了。需要明确的是,如果可以使用 --arg, --argjson 等功能代替,我认为在 jq 命令字符串中避免 shell 扩展是一种很好的做法。
    • Re "我认为在 jq 命令字符串中避免 shell 扩展是一种很好的做法,", 100%!永远不要从 shell 生成 jq 代码(或 Perl 代码,或...)。使用 --arg (或类似的)或环境是要走的路。
    【解决方案2】:

    the jq manual中,搜索“字符串插值”

    jq --arg ad "192.168.5.5" -r '.name = "Addr \($ad)"'
    

    【讨论】:

    • 我更喜欢这种方法,但另一个答案有效,他先回答。另外,我不能投票,因为我还没有足够的声望点.....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多