Jesus Espejo
Jesus Espejo

Reputation: 1

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.

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.

Have someone successfully echoed a parseable JSON with escaped characters?

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

Upvotes: 0

Views: 1952

Answers (1)

pmf
pmf

Reputation: 36131

Your variable content is already JSON-encoded. 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):

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

Upvotes: 1

Related Questions