vishnu
vishnu

Reputation: 4599

removing the backslashes in json string using the 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, "");

Upvotes: 4

Views: 10107

Answers (3)

Terry Li
Terry Li

Reputation: 17268

Solution:

var response = {"_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 body = JSON.parse(response._body);
console.log(body.error);

Explanation:

You have a top level object with one key, _body. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. Unless you are able to fix the server side code, you have to decode the nested JSON manually.

Upvotes: 1

Atul Sharma
Atul Sharma

Reputation: 10665

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

Upvotes: 3

Joe
Joe

Reputation: 2540

var obj = JSON.parse(response)

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

console.log(obj);

Upvotes: 1

Related Questions