转义JSON字符串中的双引号

时间:2014-04-30 08:01:58

标签: javascript json

我在这里有一个真正的大脑块,看起来太简单了。如何在单引号的JSON字符串中转义双引号字符串:

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

我试过了:

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

每个都会导致各种语法错误。预期产出是:

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

3 个答案:

答案 0 :(得分:2)

我可能错了......但是因为你希望输出是

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

你应该通过像这样嘲笑它来尝试它:

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

答案 1 :(得分:2)

如果你想要

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

然后注意你只需要转义反斜杠,因为"在单引号中没有特殊含义:

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

答案 2 :(得分:2)

我试过

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

作品。