从节点返回的json中的斜杠

从节点返回的json中的斜杠

本文介绍了从节点返回的json中的斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Node服务器返回的json中出现斜线.这给解析json带来了挑战.

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

json看起来像

"{\"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将其转换回json

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

当我尝试将其解析为JSON对象时,它会在

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

var obj = JSON.parse(str);

由于斜杠仍然存在,因此JSON似乎仍然无效.

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

我有以下查询-

  1. 如何更新我的正则表达式以消除这些斜线
  2. 为什么在响应中引入这些斜线

推荐答案

JSON.stringify()是用于生成 JSON字符串的方法.如果将其应用于已经是JSON字符串的内容,则会得到经过双重编码的JSON字符串:

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

您需要使用的是 JSON .parse()方法:

var alreadyJson = '{"foo": "bar"}';
var decoded = JSON.parse(alreadyJson);
console.log(decode, typeof decoded);
{ foo: 'bar' } 'object'

这篇关于从节点返回的json中的斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:58