如何用反斜杠转义的双引号回显jq JSON

bsxbgnwa  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(151)

我正在尝试创建一个函数,该函数使用带有反斜杠的转义值(如"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
rqcrx0a6

rqcrx0a61#

您的变量内容已经进行了JSON编码。使用变量时请使用引号:

jq . <<< "$jsonWithEscapedCharacters"
{
  "fields": {
    "System.AreaPath": "Here\\double-backslah",
    "System.IterationPath": "Ahother\\Double-backslash",
    "System.Title": "The \"title\" with double quotes"
  }
}

同样,要检索某个值(注意使用-r剥离JSON编码):
一个二个一个一个
存储该值时的命令替换也是如此:

title="$(jq -r '.fields."System.Title"' <<< "$jsonWithEscapedCharacters")"
echo "$title"
The "title" with double quotes

相关问题