econ
econ

Reputation: 547

bash: exact reproduction of escaped quotes in a JSON file

How is it possible to reproduce a string exactly as it is in a while-read loop?

Here's the specific example.

I am reading a JSON file: {"key":"value with a \"quote\" inside"} and piping this into a while-read loop:

echo "{\"key\":\"value with a \\\"quote\\\" inside\"}" | jq -rc '.' | while read line; do echo "$line"; done

This is the output I see:

{"key":"value with a "quote" inside"}

The quotes inside the field disappear after being echo-ed. I would like to preserve those escape characters, so I looked at possible solutions and I suspect that printf can help (Escape FileNames Using The Same Way Bash Do It). By changing echo to printf '%q':

echo "{\"key\":\"value with a \\\"quote\\\" inside\"}" | jq -rc '.' | while read line; do printf '%q' "$line"; done

I get the following:

\{\"key\":\"value\ with\ a\ \"quote\"\ inside\"\}

Unfortunately, now the previously unescaped quotes are also escaped (in addition to all the other escapes). Could you tell me how can I achieve the following output within a while read loop?

{"key":"value with a \"quote\" inside"}

Upvotes: 3

Views: 527

Answers (1)

jandob
jandob

Reputation: 659

echo "{\"key\":\"value with a \\\"quote\\\" inside\"}" | while read -r line
do 
    echo "$line"
done

works for me. With the -r switch read does not interpret backslashes. But

echo '{"key":"value with a \"quote\" inside"}' | while read -r line
do 
    echo "$line"
done

works as well

Upvotes: 4

Related Questions