Documentation Menu

Logging cyclic references

Some objects have cyclic references. That is, they refer to themselves. For example:

var a = { x: 1 };
a.self = a;

The problem is that the JSON.stringify method used to serialize objects into strings cannot handle this. Instead, it throws an exception, such as:

Uncaught TypeError: Converting circular structure to JSON

The solution is to use the JL.serialize option to set a custom method that does handle cyclic references:

  1. Find yourself a library that deals with cyclic references. Personally I like cycle.js.
  2. Write a method that takes an object, serializes it, and returns the resulting string. Such as this:

    <script src="cycle.js"></script>
    var decyclingSerializer = function(obj) {
        // JSON.decycle is defined in cycle.js
        var decycledObject = JSON.decycle(obj);
        return JSON.stringify(decycledObject);
  3. Tell JSNLog to use your new method:

        "serialize": decyclingSerializer