Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  192] [ 5]  / answers: 1 / hits: 16318  / 13 Years ago, mon, october 10, 2011, 12:00:00

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?


More From » json

 Answers
165

'{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



Parse error on line 2:
{ test: -}
-------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['


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



var test = '{test: \\-}';


Otherwise, omit it:



var test = '{test: -}';

[#89694] Saturday, October 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elaine

Total Points: 628
Total Questions: 111
Total Answers: 104

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
;