所以我猜对了一半,但我错过了另一半,
输入是
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
我错过了什么?
答案 0 :(得分:6)
如何用双引号将变量括起来 [在 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
答案 1 :(得分:-2)
没关系,
jq 'if .tweet | contains('\"$p\"') then . |= . + {'$p': 1} else . |= . + {'$p': 0} end' newfirst.json