我有带有反斜杠的 JSON 响应,有些响应不包含反斜杠。
我需要根据响应显示错误消息,如何使用 javascript 解析 JSON 响应?
不带反斜杠的 JSON 响应,
{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null}
用反斜杠响应,
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
我尝试了以下方式,但它仅适用于没有反斜杠的 JSON 响应。
var strj = JSON.stringify(err._body);
var errorobjs = strj.replace(/\\/g, "");
最佳答案
实际上问题不在于 /
斜杠。 JSON 无效
。
从后端服务器中删除这些"
{"_body":"{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"}","status":500,"ok":false,"statusText":"Internal Server Error"}
double quote
before "{"timestamp and one after login""
这两个突出显示,您的代码将起作用。
var data = '{"_body":{\"timestamp\":\"2016-11-18T04:46:18.972+0000\",\"status\":500,\"error\":\"Internal Server Error\",\"exception\":\"java.lang.ArrayIndexOutOfBoundsException\",\"message\":\"1\",\"path\":\"/login\"},"status":500,"ok":false,"statusText":"Internal Server Error"}';
var json_data = JSON.parse(data);
console.log(json_data);
您实际上在后端将 body
对象包装在字符串中,这是无效的。
"body" : "bodyOBJ" //Invalid
"body" : bodyObj //Valid
关于javascript - 使用 javascript 删除 json 字符串中的反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40669673/