gpt4 book ai didi

javascript - 使用 javascript 删除 json 字符串中的反斜杠

转载 作者:行者123 更新时间:2023-11-29 21:13:18 25 4
gpt4 key购买 nike

我有带有反斜杠的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com