【问题标题】:How to wrap double quotes around a variable如何在变量周围加上双引号
【发布时间】:2021-06-27 13:24:48
【问题描述】:

所以我知道我得到了一半,但另一半我错过了,

输入是

echo $p
jq 'if .tweet | contains('\"$p\') then . |= . + {'$p': 1} else . |= . + {'$p': 0} end' newfirst.json

我得到的输出是

if .tweet | contains("accelerite) then . |= . + {accelerite: 1} else . |= . + {accelerite: 0} end

我想要的输出是

if .tweet | contains("accelerite") then . |= . + {"accelerite": 1} else . |= . + {"accelerite": 0} end

我错过了什么?

【问题讨论】:

    标签: bash shell escaping jq


    【解决方案1】:

    如何在变量周围加上双引号 [在 jq 脚本中使用]

    编写您自己的转义函数,遵循 json 规范并正确传递转义字符串。编写这样的函数并非易事 - 研究 jq 文档和源代码,了解它如何解释参数和 json 文档,了解字段中允许哪些字符以及如何转义它们。


    编写这样的函数会很麻烦,而是将变量传递给 jq 并让 jq 解决。研究 jq 文档并在 shell 中引用。

    jq --arg p "$p" 'if .tweet | contains($p) then . |= . + {$p: 1} else . |= . + {$p: 0} end' newfirst.json
    

    【讨论】:

      【解决方案2】:

      没关系,

      jq 'if .tweet | contains('\"$p\"') then . |= . + {'$p': 1} else . |= . + {'$p': 0} end' newfirst.json
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多