ae701 ae701 -4 years ago 327
JSON Question

JSON slashes and backslashes in string on bourne shell

I am trying to parse json files that contain sequences of slashes and backslashes in some of their strings like this:

echo '{"tag_string":"/\/\/\ test"}' | jq


which gives me:

parse error: Invalid escape at line 1, column 27


I have tried escaping with backslashes at different positions, but I can't seem to find a correct way. How do I output the string as it is, without removing any character or getting errors?

This only works on bash, but not sh (or zsh):

echo '{"tag_string":"/\\/\\/\\ test"}' | jq -r '.tag_string'
/\/\/\ test

Answer Source

If you are trying to include literal backslashes:

(bash)

echo '{"tag_string":"/\\/\\/\\ test"}' | jq
{
  "tag_string": "/\\/\\/\\ test"
}

echo '{"tag_string":"/\\/\\/\\ test"}' | jq -r '.["tag_string"]'
/\/\/\ test

(sh)

echo '{"tag_string":"/\\\\/\\\\/\\\\ test"}' | jq -r '.["tag_string"]'
/\/\/\ test

printf "%s" '{"tag_string":"/\\/\\/\\ test"}' | jq -r '.["tag_string"]'
/\/\/\ test
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download