I have a string in javascript:
var test = '{"test":"\\-"}'
When I try to parse this as JSON with the following:
JSON.parse(test)
or with:
$.parseJSON(test)
I get a SyntaxError of type “unexpected_token_number”.
This the value for the "test" attribute is a user enterable field. How should I properly escape this field?
'{"test":"\\-"}'will be interpreted as JavaScript string, with the result being{"test":"\-"}.As you can see in these diagrams,
\-is not a valid escape sequence (valid are\",\\,\/,\b,\f,\n,\r,\t,\uxxxx).JSONLint also gives the error
If you want two backslashes in the JSON you have to escape them in the JavaScript string as well, so you’d end up with
Otherwise, omit it: