[英]How to prettify json with jq given a string with escaped double quotes
[英]How to echo a jq JSON with double quotes escaped with backslash
我正在尝试创建一个 function 来回显 a JSON,其转义值带有反斜杠,如"System.Title": "The \"title\" with double quotes"
属性,当 jq 处理回显结果时返回解析错误。
正如您在注释行中看到的那样,我已经尝试了几种方法来抵消echo
显对反斜杠的影响,但我仍然无法回显可解析的 JSON。
有人用转义字符成功回显了可解析的 JSON 吗?
jsonWithEscapedCharacters='{
"fields": {
"System.AreaPath": "Here\\double-backslah",
"System.IterationPath": "Ahother\\Double-backslash",
"System.Title": "The \"title\" with double quotes"
}
}'
getjsonWithEscapedCharacters() {
# FAIL echo $jsonWithEscapedCharacters | sed 's/\\/\\\\/g'
# FAIL echo "$jsonWithEscapedCharacters" | sed 's/\\/\\\\/g'
# FAIL echo -E "$jsonWithEscapedCharacters" | sed 's/\\/\\\\/g'
# FAIL echo "$jsonWithEscapedCharacters"
# FAIL echo -e $jsonWithEscapedCharacters
echo -e $jsonWithEscapedCharacters
}
echoedJson=$(getjsonWithEscapedCharacters)
titleFromJson=$(jq '.fields["System.Title"]' <<< $jsonWithEscapedCharacters)
title=$(jq '.fields["System.Title"]' <<< $echoedJson)
echo "expected $titleFromJson, actual: $title"
# jsonWithEscapedCharacters is parsed OK but echoedJson cannot be parsed due to jq Parse error
您的变量内容已经过 JSON 编码。 使用变量时只需使用引号:
jq . <<< "$jsonWithEscapedCharacters"
{
"fields": {
"System.AreaPath": "Here\\double-backslah",
"System.IterationPath": "Ahother\\Double-backslash",
"System.Title": "The \"title\" with double quotes"
}
}
同样,要检索一些值(请注意使用-r
去除 JSON 编码):
jq -r '.fields."System.Title"' <<< "$jsonWithEscapedCharacters"
The "title" with double quotes
与存储该值时的命令替换类似:
title="$(jq -r '.fields."System.Title"' <<< "$jsonWithEscapedCharacters")"
echo "$title"
The "title" with double quotes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.