CodingIntrigue
CodingIntrigue

Reputation: 78525

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:

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

var obj = {
  "quote": "\"Hello World\", he said."
};

Upvotes: 3

Views: 11104

Answers (3)

Jiang Nan
Jiang Nan

Reputation: 52

I tried

var json = '{ "quote": "\\"Hello World\\", he said." }';

Works.

Upvotes: 2

Pablo Lozano
Pablo Lozano

Reputation: 10342

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." }'

Upvotes: 3

Oliver Schaub
Oliver Schaub

Reputation: 71

I might be wrong... but since you ecpect the output to be

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

You should try it by maskin it like this:

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

Upvotes: 2

Related Questions