Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape double quotes in JSON string

I'm having a real brain-block here for something which seems too simple. How can I escape double-quoted strings in a single-quoted JSON string:

var json = '{ "quote": ""Hello World", he said." }';
var obj = JSON.parse(json);

I've tried:

  • '{ "quote": "\"Hello World\", he said." }'
  • '{ "quote": "\\\"Hello World\\\", he said." }'
  • '{ "quote": """Hello World"", he said." }'

Each of which results in various syntax errors. Expected output is:

var obj = {
  "quote": "\"Hello World\", he said."
};
like image 643
CodingIntrigue Avatar asked Jun 24 '26 11:06

CodingIntrigue


1 Answers

If you want

{ "quote": "\"Hello World\", he said." }

then notice you have to escape the backslashes only, because " has no especial meaning within single quotes:

'{ "quote": "\\"Hello World\\", he said." }'
like image 116
Pablo Lozano Avatar answered Jun 25 '26 23:06

Pablo Lozano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!