我从Node服务器返回的json中得到斜杠.这给解析json带来了挑战.
json看起来像
"{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\\"15-HeifZ4bmt+WxpIWDoartGQ\\"\"},\"response\":\"{\\"status\\":\\"UP\\"}\",\"bytesSent\":715779}"
Run Code Online (Sandbox Code Playgroud)
为了摆脱斜杠,我做了一个替换,然后使用JSON.parse将其转换回json
.then(function (result) {
var status = "";
var str = JSON.stringify(result);
console.log("str result ", str);
str = str.replace(/\\/g, "");
console.log("result after cleanup ", str);
var obj = JSON.parse(str);
status = obj.response.status;
}
Run Code Online (Sandbox Code Playgroud)
替换斜杠后,字符串看起来像这样
"{\"responseCode\":200,\"headers\":{\"Access-Control-Allow-Origin\":\"*\",\"Content-Type\":\"application/json; charset=utf-8\",\"X-Powered-By\":\"Express\",\"Connection\":\"keep-alive\",\"Date\":\"Thu, 22 Sep 2016 08:12:39 GMT\",\"Content-Length\":\"21\",\"Etag\":\"W/\"15-HeifZ4bmt+WxpIWDoartGQ\"\"},\"response\":\"{\"status\":\"UPLOADED\"}\",\"bytesSent\":715779}"
Run Code Online (Sandbox Code Playgroud)
当我尝试将其解析为JSON对象时,它会抛出错误
var obj = JSON.parse(str);
Run Code Online (Sandbox Code Playgroud)
由于仍存在斜杠,JSON似乎仍然无效.
我有以下疑问 -