替换“与\”

时间:2014-02-09 17:53:36

标签: javascript regex json string

我正在尝试将所有"替换为\"并使用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 个答案:

答案 0 :(得分:5)

重点是使用2 \

b = b.replace(/"/g,'\\"')

结果是:

[\"{\"objects\":[],\"background\":\"#fff\"}\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"]
正如@isherwood所说:

  

更清楚的是,反斜杠是一个转义字符,所以你需要   加倍,所以逃跑背后有一个真正的角色。

答案 1 :(得分:1)

尝试使用:

b = b.replace(/"(?=[^\{]*\})/g, '\\"');

这会将大括号内的所有"替换为\"

第一个字符串a实际上变为:

["{\"objects\":[],\"background\":\"#fff\"}","","","","","","","","",""]

这就是你必须要做的b,除了在制作变量之后,它变为:

["{"objects":[],"background":"#fff"}","","","","","","","","",""]

所以你实际上必须把一些\放回原处。

但是,既然您正在尝试解析JSON,那么最好使用:

b = JSON.stringify(b);