简体   繁体   English

jq双反斜杠有时已删除

[英]jq double backslash sometime removed

I have a first json file like this: 我有一个像这样的第一个json文件:

{
  "env_vars": {
    "TERRAFORM_CFG_TLS_CERT": "-----BEGIN CERTIFICATE----\\nMIIIqzCCB5O"
  }
}

If I use the command: 如果我使用命令:

echo <file> | jq -r '.env_vars'

The result is as expected (the backslash are still there): 结果与预期的一样(反斜杠仍然存在):

{
  "TERRAFORM_CFG_TLS_CERT": "-----BEGIN CERTIFICATE----\\nMIIIqzCCB5O"
}

But if i execute this command: 但是,如果我执行此命令:

cat <file> | jq -r '.env_vars' | jq -r 'keys[] as $k | "\($k)=\"\(.[$k])\""'

The result is: 结果是:

TERRAFORM_CFG_TLS_CERT: "-----BEGIN CERTIFICATE----\nMIIIqzCCB5O"

=> One backslash has been removed... why ? =>已删除一个反斜线...为什么? How to avoid this ? 如何避免这种情况?

Thanks. 谢谢。

Using the -r option tells jq to "translate" the JSON string into a "raw" string by interpreting the characters that are special to JSON (see eg http://json.org ). 使用-r选项告诉jq通过解释JSON特有的字符(参见例如http://json.org )将JSON字符串“转换”为“原始”字符串。 Thus, following the [mcve] guidelines a bit more closely, we could start with: 因此,更严格地遵循[mcve]准则,我们可以开始:

$ jq . <<< '"X\\nY"'
"X\\nY"

$ jq -r . <<< '"X\\nY"'
X\nY

If you check the json.org specification of strings, you'll see this is exactly correct. 如果检查字符串的json.org规范,您会发现这是完全正确的。

So if for some reason you want each occurrence of \\\\ in the JSON string to be replaced by two backslash characters (ie JSON: "\\\\\\\\" ), you could use sub or gsub . 因此,如果出于某种原因您希望用两个反斜杠字符(即JSON: "\\\\\\\\" )替换JSON字符串中\\\\每个出现,可以使用subgsub That's a bit tricky, because the first argument of these functions is a regex. 这有点棘手,因为这些函数的第一个参数是正则表达式。 Behold: 看吧:

$ jq -r 'gsub("\\\\"; "\\\\")' <<< '"X\\nY"'
X\\nY

You should output the string as json to preserve the escapes. 您应该将字符串输出为json以保留转义符。 By taking a string and outputting it raw, you're getting exactly what that string was, a literal backslash followed by an n . 通过获取字符串并将其输出为原始字符串,您将确切地知道该字符串是什么,即文字反斜杠后跟n

$ ... | jq -r '.env_vars | to_entries[] | "\(.key): \(.value | tojson)"'

If any of the values are non-strings, add a tostring to the filter. 如果任何值都是非字符串,则将tostring添加到过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM