我正在尝试用 \"
替换所有 "
并用 JSON 解析字符串,但浏览器抛出错误 SyntaxError: JSON Parse error: Unrecognized token '\'
.
下面是代码。字符串 a 的 JSON.parsed 很好,但是尽管我将字符串 b 中的所有 "
替换为 \"
,因此它应该与字符串 a 相同,但解析失败。我在 JSBIN 中有代码.
var a = '[\"{\\"objects\\":[],\\"background\\":\\"#fff\\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]';
var b = '["{\"objects\":[],\"background\":\"#fff\"}","","","","","","","","",""]';
// Replace " with \"
// Charcode 92 is \
b = b.replace('"', String.fromCharCode(92)+'"', "g");
a = JSON.parse(a);
console.log(a);
b = JSON.parse(b);
console.log(b);
知道吗,我如何使用 JSON.parse 解析字符串 b?如果我手动将所有 "
替换为 \"
,它会很好地解析,但我正在寻求自动化的方式。
最佳答案
重点是使用 2 \
:
b = b.replace(/"/g,'\\"')
结果是:
[\"{\"objects\":[],\"background\":\"#fff\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]
正如@isherwood 所说:
To be more clear, the backslash is an escape character, so you need to double it so there's an actual character behind the escape.
关于javascript - 替换 "with\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662695/