我得到一个JSON字符串,其中包含一个数据字段中的另一个JSON字符串,使用\进行转义,并被"包围&#34 ;.在解析之前我想删除它们。我用regexp替换:
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 :(得分:2)
没有必要执行任何字符串替换来取消内部字符串。相反,您可以将外部字符串加载到变量中,并通过数组键或属性来定位内部字符串。找到后,你可以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"}