我创建了一个从http响应中读取数据的应用程序。数据以JSON形式返回,JSON字符串包含反斜杠,其中双引号被转义。
我已尝试过此处演示的示例Android: Parsing JSON string inside of double quotes。
这是我的榜样:
var data="\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\""
var escapeSlashes = data.replace("\\\"/g", "\"");
它返回如下:
[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]
尝试解析时代码中断。
var obj = $.parseJSON(escapeSlashes);
除了进行替换之外,还有其他方法可以处理吗?
答案 0 :(得分:3)
好吧,所以..它真的只是JSON,几次逃脱。超级愚蠢的事情,但如何解决这个问题?
让多次unescape !
我们走了:
var moo = "\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\"";
// Don't let the backslashes confuse you
// What the string really contains is here:
console.log(moo);
// "[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]"
// That's a JSON string, see the quotes at the ends?
// Let's parse!
var moo2 = JSON.parse(moo);
console.log(moo2);
// [{"FirstName":"John","LastName":"Doe"}]
// Alright, looks like a regular JSON array with one object in it.
// Crack it open!
var moo3 = JSON.parse(moo2);
console.log(moo3);
// Hole cow, we got a JS Object!
// [Object { FirstName="John", LastName="Doe"}]
// Do whatever you want with it now...