Skip to content Skip to sidebar Skip to footer

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-

Solution 1:

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'

Solution 2:

You don't need regx to eliminate slashes.

var response = '{\"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}';
JSON.parse(response);

This will give you JSON object eliminating slashes. Reference

Solution 3:

If I put some newlines in your string, it 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\\":\\"UP\\"}\",
  \"bytesSent\":715779
}"

We can see that one of the issue is at line Etag. The part \\"15 should be \\\"15. One backslash to espace the next backslash, then again a backslash to espace the quote.

It's the same issue for status and UP. Fix your server :)

Post a Comment for "Slashes In Json Returned From Node"