Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slashes in json returned from node

I am getting slashes in the json returned from Node server. This is giving challenges in parsing the json.

The json looks like

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

In order to get rid of the slashes, I did a replace and then converted it back to json using JSON.parse

.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;
}

After replacing the slashes, the string looks like this

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

When I try to parse it to JSON object, it throws an error on

var obj = JSON.parse(str);

It seems that the JSON is still invalid due to the slashes which still exist.

I have the following queries -

  1. How can I update my regex to get rid of these slashes as well
  2. Why do these slashes get introduced in the response
like image 509
kayasa Avatar asked Dec 11 '22 14:12

kayasa


1 Answers

JSON.stringify() is the method used to generate a JSON string. If you apply it to something that's already a JSON string then you'll get a double-encoded JSON string:

var alreadyJson = '{"foo": "bar"}';
var doubleEncoded = JSON.stringify(alreadyJson);
console.log(doubleEncoded , typeof doubleEncoded);
"{\"foo\": \"bar\"}" string

What you need to use is the JSON.parse() method:

var alreadyJson = '{"foo": "bar"}';
var decoded = JSON.parse(alreadyJson);
console.log(decode, typeof decoded);
{ foo: 'bar' } 'object'
like image 199
Álvaro González Avatar answered Jan 06 '23 20:01

Álvaro González