2015-02-08 149 views
0

我得到一个JSON字符串,它在一个数据字段中包含另一个JSON字符串,用\和\“\”包围。我喜欢在解析它们之前删除它们。我用正则表达式替换:正则表达式:从JSON字符串中删除转义字符

var data = evt.data.replace(/\\\"/g,"\""); 
data = data.replace(/\"\{/g,"{"); 
data = data.replace(/\}\"/g,"}"); 

输入字符串:

{"data":[{"beehive":"yaylaswiese","gamestate":"{\"currentGame\":\"StorieS3\"}","magicspell":"","sid":"40cc9dba822746fd572cece0416b320426759cc8"}],"sid":"login"} 

应该是:

{"data":[{"beehive":"yaylaswiese","gamestate":{"currentGame":"StorieS3"},"magicspell":"","sid":"40cc9dba822746fd572cece0416b320426759cc8"}],"sid":"login"} 

我的作品,但它看起来很复杂,以取代\ “用”,“{与{和}“与}

有没有更简单的解决方案?

+0

请张贴输入字符串的示例。看起来你应该能够解析外部字符串,然后定位包含内部字符串的元素并分别解析该字符串。 – 2015-02-08 19:24:38

+0

我在上面添加了它。 – Michael 2015-02-08 19:29:17

+0

你如何得到这个字符串?内部的一个应该是可解析的,假设整个东西被加载到一个对象'JSON.parse(obj.data [0] .gamestate)' – 2015-02-08 19:41:23

回答

2

有没有必要执行任何字符串替换unescape内部字符串。相反,您可以将外部字符串加载到变量中,并通过数组键或属性来定位内部字符串。当发现时,你可以在JSON.parse()的内部:

// Storing the main string in a variable 
var outer = {"data":[{"beehive":"yaylaswiese","gamestate":"{\"currentGame\":\"StorieS3\"}","magicspell":"","sid":"40cc9dba822746fd572cece0416b320426759cc8"}],"sid":"login"}; 

// The inner string is accessible at 
var inner = outer.data[0].gamestate; 
// "{"currentGame":"StorieS3"}" 

// Parse it: 
JSON.parse(inner); 
// Object {currentGame: "StorieS3"}