Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing the backslashes in json string using the javascript

Tags:

javascript

i have JSON response which is having backslashes and some responses are not containing the backslashes.

I need to show error message based on the response, How do i parse the JSON response using javascript?

JSON response with out backslashes,

{"_body":{"isTrusted":true},"status":0,"ok":false,"statusText":"","headers":{},"type":3,"url":null} 

response with backslashes,

{"_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"}

i tried in the following way but it is working only for JSON response which is not having the backslashes.

var strj = JSON.stringify(err._body);
 var errorobjs = strj.replace(/\\/g, "");
like image 201
vishnu Avatar asked Sep 07 '25 18:09

vishnu


2 Answers

Actually the problem is not with / slashs. The JSON is INVALID.

remove these " from backend server

{"_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"}" these two highlighted and your code will work.

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);

You are actually wrapping body object in string at backend which is not valid.

"body" : "bodyOBJ"  //Invalid
"body" : bodyObj    //Valid
like image 110
Atul Sharma Avatar answered Sep 10 '25 10:09

Atul Sharma


var obj = JSON.parse(response)

if(typeof obj._body == "string") {
    obj._body = JSON.parse(obj._body)
}

console.log(obj);
like image 20
Joe Avatar answered Sep 10 '25 09:09

Joe