Serializing object that contains cyclic object value

Asked
Active3 hr before
Viewed126 times

8 Answers

containsvalueobject
90%

I create too a github project that can serialize cyclic object and restore the class if you save it in the serializename attribute like a String ,cycle in the object definition,Thanks for contributing an answer to Stack Overflow!,https://github.com/bormat/serializeStringifyParseCyclicObject

Use the second parameter of stringify, the replacer function, to exclude already serialized objects:

var seen = [];

JSON.stringify(obj, function(key, val) {
   if (val != null && typeof val == "object") {
      if (seen.indexOf(val) >= 0) {
         return;
      }
      seen.push(val);
   }
   return val;
});

For example, for:

a = {
   x: 1
};
obj = [a, a];
function decycle(obj, stack = []) {
   if (!obj || typeof obj !== 'object')
      return obj;

   if (stack.includes(obj))
      return null;

   let s = stack.concat([obj]);

   return Array.isArray(obj) ?
      obj.map(x => decycle(x, s)) :
      Object.fromEntries(
         Object.entries(obj)
         .map(([k, v]) => [k, decycle(v, s)]));
}

//

let a = {
   b: [1, 2, 3]
}
a.b.push(a);

console.log(JSON.stringify(decycle(a)))
load more v
88%

The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly. , The JSON format per se doesn't support object references (although an IETF draft exists), hence JSON.stringify() doesn't try to solve them and fails accordingly. ,JavaScript error reference,JSON.stringify() will fail

TypeError: cyclic object value(Firefox)
TypeError: Converting circular structure to JSON(Chrome and Opera)
TypeError: Circular reference in value argument not supported(Edge)
load more v
72%

The JavaScript exception "cyclic object value" occurs when object references were found in JSON. JSON.stringify() doesn't try to solve them and fails accordingly.,The JSON format per se doesn't support object references (although an IETF draft exists), hence JSON.stringify() doesn't try to solve them and fails accordingly.,JSON.stringify() will fail,The snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of JSON.stringify():

Message

TypeError: cyclic object value(Firefox)
TypeError: Converting circular structure to JSON(Chrome and Opera)
TypeError: Circular reference in value argument not supported(Edge)
load more v
65%

I'd like to serialize this object, using JSON.stringify(), but I get : TypeError: cyclic object value because of the constructs I mentioned. , c# - Json.net How to serialize an object to a value , Serialize typesafe config object , serialization - Serialize the Navigator object of JavaScript

I have an object (parse tree) that contains child nodes which are references to other nodes.

I'd like to serialize this object, using JSON.stringify(), but I get : TypeError: cyclic object value because of the constructs I mentioned.

JSON.stringify()
load more v
75%

I'm getting error [TypeError: JSON.stringify cannot serialize cyclic structures.] object when i try to convert realm object to json object using JSON.parse(JSON.stringify(item)) ,This is not a bug in Realm. This is due to the circular structure within item.,Yes toJSON() returns the same structure, where instances of Realm.Object & Realm.Collection has been replaced by flat JS objects & arrays. For more info on toJSON, see MDN toJSON.,Successfully merging a pull request may close this issue.

const chats = realm.objects('Chat');
const serialized = JSON.stringify(chats, Realm.JsonSerializationReplacer)
load more v
40%

I created a Building object that had a 'marker' property (and some other properties). The 'marker' property contained a Google Map Marker, and I'm not sure of it's internals, but when I tried to use JSON.stringify() on it, I got a 'cyclic object value' error. After digging around, I found that you can pass in a second param to stringify(), which is a function that you can use to override the values of properties in the output string. In this case I used it to exclude the marker property from the string.

var json = JSON.stringify(buildingObj, function(key, value) {
   if (key == "marker") {
      return undefined;
   }
   return value;
});
22%

Not all objects can be converted to a JSON string. When an object has cyclic self-references, the conversion will fail.,This is typically the case for hierarchical data structures where parent and child both reference each other:,As soon as the process detects a cycle, the exception is raised. If there were no cycle detection, the string would be infinitely long., Serializing and restoring class instances

This is typically the case for hierarchical data structures where parent and child both reference each other:

const world = {
   name: 'World',
   regions: []
};

world.regions.push({
   name: 'North America',
   parent: 'America'
});
console.log(JSON.stringify(world));
// {"name":"World","regions":[{"name":"North America","parent":"America"}]}

world.regions.push({
   name: 'Asia',
   parent: world
});

console.log(JSON.stringify(world));
// Uncaught TypeError: Converting circular structure to JSON
60%

const getCircularReplacer = () => {
   const seen = new WeakSet();
   return (key, value) => {
      if (typeof value === "object" && value !== null) {
         if (seen.has(value)) {
            return;
         }
         seen.add(value);
      }
      return value;
   };
};

JSON.stringify(circularReference, getCircularReplacer());
load more v

Other "contains-value" queries related to "Serializing object that contains cyclic object value"