Converting circular structure to JSON in Angularjs

I am using AngualrJS and via service call getting a response and it returns a JSON object like

response={TypeName:sample,MessageType:0,Message1: null,Message2:null,Foo:0}.

In angularjs I have code like this

var a= angular.fromJson(angular.toJson(response))   //Getting error "TypeError: Converting circular structure to JSON"

How can I fix this.Is this issue with API data or am I doing anything wrong in Angularjs

Thanks in advance

Hi,

Assuming that sample is defined elsewhere, the code you provided should run without an error:

var sample = "sample";

var response = {
  TypeName: sample,
  MessageType:0,
  Message1: null,
  Message2:null,
  Foo:0
};

console.log(response);

// Outputs: 
// [object Object] {
//    Foo: 0,
//    Message1: null,
//    Message2: null,
//    MessageType: 0,
//    TypeName: "sample"
// }

var a = angular.fromJson(angular.toJson(response));
console.log(a);

// Outputs: 
// [object Object] {
//    Foo: 0,
//    Message1: null,
//    Message2: null,
//    MessageType: 0,
//    TypeName: "sample"
// }

I’m not sure why you would want to do this, however: angular.toJson serializes input into a JSON-formatted string, whereas angular.fromJson deserializes a JSON string. So by doing angular.fromJson(angular.toJson(response)); you are converting the JSON object you are receiving into a deserialized string, then converting the string back into a JSON object. It’s the same as writing: var a = reponse;

Regarding your error: it means that the object you pass to angular.toJSON has a circular reference, something like:

var a = {};
a.b = a;

angular.toJSON cannot convert structures like this.

Thank you so much for your detailed explanation.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.