I have a JSON object in my node.js code which contains circular references. To send this data to the browser, I used the NPM module circular-json to stringify the object and serialise the circular references:
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));
});
});
This works fine and sends serialised data through res.send();
Now, in my frontend Angular code I need to make the circular references usable. One of the serialised fields in the object looks like this on the client side: "~0~fields~twitter~1"
I tried the following in the browser:
circular-json.js
to my frontend siteindex.html
like so: <script src="/framework/lib/circular-json.js"></script>
CircularJson
variable like so: var CircularJSON = window.CircularJSON;
Parse the incoming JSON like so:
$http.get("/api/entries").then(function(res){
console.log(CircularJSON.parse(res.data[0]));
});
I get the following error:
SyntaxError: Unexpected token o
For one time call I think you can use $http as follows
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);
})
});
Or for every call you can define an interceptors, examples are here: https://docs.angularjs.org/api/ng/service/$http
UPDATE: Unshift does not return the array. Modified the code, now it should work.