【问题标题】:Parse JSON serialised by CircularJSON解析由 CircularJSON 序列化的 JSON
【发布时间】:2015-07-28 09:46:27
【问题描述】:

我的 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

【问题讨论】:

  • 您可能必须在客户端使用相同的库。
  • @FelixKling Yeh 我想是这样,但我不知道该怎么做。我按照他们的指南进行操作,但没有成功。
  • 如果您发布您尝试过的内容并解释问题所在,我们或许可以为您提供帮助。
  • 好的,我会更新我的问题
  • @FelixKling 我已经更新了用于解析 JSON 的前端代码

标签: javascript json angularjs node.js contentful


【解决方案1】:

一次性调用我认为你可以使用 $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

更新: Unshift 不返回数组。修改了代码,现在应该可以了。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2013-05-17
  • 1970-01-01
  • 2015-09-21
  • 2017-07-27
  • 1970-01-01
相关资源
最近更新 更多