ae701
ae701

Reputation: 23

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

Upvotes: 1

Views: 3279

Answers (3)

obelix15012
obelix15012

Reputation: 101

A forward slash character is legal, but a single backslash character is not. According to json.org char description, the valid chars are:

char
    any-Unicode-character-
        except-"-or-\-or-
        control-character
    \"
    \\
    \/
    \b
    \f
    \n
    \r
    \t
    \u four-hex-digits 

So in your example, the single backslashes are not legal, you need either "\\" which is interpreted as double backslashes, or you need to remove them entirely.

Upvotes: 2

peak
peak

Reputation: 116750

If you are trying to convert a file with non-JSON strings, then consider a tool such as any-json. Using the "cson-to-json" mode, "\/" will be interpreted as "/":

$ any-json -format=cson

Input:

{"tag_string":"/\/\/\ test"}

Output:

{
  "tag_string": "/// test"
}

Upvotes: 0

peak
peak

Reputation: 116750

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

Upvotes: 0

Related Questions