简体   繁体   English

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

[英]How to echo a jq JSON with double quotes escaped with backslash

I'm trying create a function that echoes the a JSON with escaped values with backslash like "System.Title": "The \"title\" with double quotes" property and when jq processes the echoed result returns a Parse error.我正在尝试创建一个 function 来回显 a JSON,其转义值带有反斜杠,如"System.Title": "The \"title\" with double quotes"属性,当 jq 处理回显结果时返回解析错误。

As you can see in the commented lines I've tried several ways to offset the effects of echo on backslash but I still cannot echo a parseable JSON.正如您在注释行中看到的那样,我已经尝试了几种方法来抵消echo显对反斜杠的影响,但我仍然无法回显可解析的 JSON。

Have someone successfully echoed a parseable JSON with escaped characters?有人用转义字符成功回显了可解析的 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

Your variable content is already JSON-encoded.您的变量内容已经过 JSON 编码。 Just use quotes when using the variable:使用变量时只需使用引号:

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

Likewise, to retrieve some value (note the use of -r to strip the JSON encoding):同样,要检索一些值(请注意使用-r去除 JSON 编码):

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

Likewise with command substitution when storing that value:与存储该值时的命令替换类似:

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

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

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