我正在尝试创建一个函数,该函数使用带有反斜杠的转义值(如"System.Title": "The \"title\" with double quotes"
属性)回显JSON,当jq处理回显结果时,返回一个Parse错误。
正如您在注解行中看到的,我尝试了几种方法来抵消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
1条答案
按热度按时间rqcrx0a61#
您的变量内容已经进行了JSON编码。使用变量时请使用引号:
同样,要检索某个值(注意使用
-r
剥离JSON编码):一个二个一个一个
存储该值时的命令替换也是如此: