解析由CircularJSON序列化的JSON

Parse JSON serialised by CircularJSON

本文关键字:JSON 序列化 CircularJSON      更新时间:2023-09-26

我的node.js代码中有一个JSON对象,它包含循环引用。为了将这些数据发送到浏览器,我使用了NPM模块circular json来字符串化对象并串行化循环引用:

var CircularJSON = require("circular-json");
app.get("/api/entries", function(req, res){ 
  contentClient.entries({"content_type": "xxxxxxxxxxx"}, function(err, entries){
    if (err) throw err;
    res.send(CircularJSON.stringify(entries));
  });
});

这工作正常,并通过res.send();发送串行数据现在,在我的前端Angular代码中,我需要使循环引用可用。对象中的一个串行字段在客户端上如下所示:"~0~fields~twitter~1"

我在浏览器中尝试了以下操作:

  1. circular-json.js的一个版本复制到我的前端站点
  2. 链接到我的index.html中的脚本,如下所示:<script src="/framework/lib/circular-json.js"></script>
  3. CircularJson变量设置为:var CircularJSON = window.CircularJSON;
  4. 像这样解析传入的JSON:

    $http.get("/api/entries").then(function(res){ console.log(CircularJSON.parse(res.data[0])); });

我得到以下错误:SyntaxError: Unexpected token o

对于一次通话,我认为您可以使用$http,如下

function appendTransform(defaults, transform) {
  // We can't guarantee that the default transformation is an array
  defaults = angular.isArray(defaults) ? defaults : [defaults];
  // Append the new transformation to the defaults
  defaults.unshift(transform);
  return defaults;
}
$http({
  url: '...',
  method: 'GET',
  transformResponse: appendTransform($http.defaults.transformResponse,                function(value) {
    return CircularJSON.parse(value);
  })
});

或者,对于每个可以定义拦截器的调用,示例如下:https://docs.angularjs.org/api/ng/service/$http

更新:取消移位不会返回数组。修改了代码,现在应该可以工作了。