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 -
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With