Reputation: 1289
I am facing one issue with below code snippet
My scenario is:
var lit = "{"foo":"test \\"1\\"","bar":"test 2"}";
console.log(lit);
var thaw2 = JSON.parse(lit);
console.log(thaw2);
Due to the double quotes in lit object, I am getting an error "unexpected identifier". I cannot chnage it to single quotes here, is there any solution to convert that string to json object with all double quotes?
Any help would be appreciated.
Upvotes: 1
Views: 2092
Reputation: 51
Cause for your issue: When double quotes are used to define a string and used as part of the string, it considers as closing quotes.
To fix this: Option 1: Use single quotes to start and end the string.
var lit = '{"foo":"test \\"1\\"","bar":"test 2"}';
This would not work in case u want to use single quotes inside ur string. In that case use option 2.
Option 2: Escaping. use \' or \" to escape the character
Eg: var lit = '{\'foo\':"test \\"1\\"","bar":"test 2"}'; (Escaping single quote)
var lit = "{\"foo\":\"test \\\"1\\\"\",\"bar\":\"test 2\"}"; (escaping double quote)
Upvotes: 0
Reputation: 2639
Use single quotations instead of double quotations for outer most boundary.
var lit = '{"foo":"test \\"1\\"","bar":"test 2"}';
console.log(lit);
var thaw2 = JSON.parse(lit);
console.log(thaw2);
Upvotes: 1
Reputation: 7594
Escape the internal double quotes.
var lit = "{\"foo\":\"test \\\"1\\\"\",\"bar\":\"test 2\"}";
console.log(lit);
var thaw2 = JSON.parse(lit);
console.log(thaw2);
Upvotes: 1