I have a variable str
let str = '{"id": "option2", "text": ""hello world""}';
when i try to convert to json using JSON.parse(str);
, it throws an error SyntaxError: Expected ',' or '}' after property value in JSON at position 28
. I’m aware that the javascript engine reads the str
as
{"id": "option2", "text": ""hello world""}
, so it’s expecting a ,
or a }
after the first set of double quotes (""
) that appear before hello world
.
Putting an extra backslash allows JSON.parse(str);
to run.
let str = '{"id": "option2", "text": "\"hello world\""}';
However, I’d like to put the extra backslash programatically. I’ve tried using the replace
method. It doesn’t seem to have any effect
let str = '{"id": "option2", "text": ""hello world""}'.replace(/\"/g, '\\"');
JSON.parse(str)
still throws the same error.
The result i’m looking for is such that when str.text
is printed on the console, it’s value should be "hello world"
2
Answers
You need to use
"
if you want to KEEP the quotesthe chalenge is that the beginning quoted words are differ from the end. And it seems like javascript has some bugs and doesn’t allow to replace "/" using replace function. So only this code works for me