0

Can we Stringify a circular object without losing data from it, I tried Flatted and other libraries but they remove data from object in which I need them. Anyone knows a way to do it please?

  • how do you expect circular object look like when it's stringified? Circular object is the object with it's properties pointing to object itself or it's other properties. So basically it could be like a fractal when printed as string. – tarkh Feb 03 '22 at 11:45
  • I just want to put the object in local storage and then use it again with the same data, if there is any workaround or i should lose hope. – Mohamad Meksasi Feb 03 '22 at 12:12
  • Ok, check my answer for details – tarkh Feb 03 '22 at 12:22

2 Answers2

2

In my opinion, The best way to do this would be to use JSON.stringify but with a custom replacer function. Extending tarkh's answer, Here's how you can stringify a circular object:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Print string
// You can see in the result, that circular
// property have **ref** link as it's value
console.log('circular one:', circular);

var cache = [];
const stringified = JSON.stringify(circular, (key, value) => {
  if (typeof value === 'object' && value !== null) {
    // Duplicate reference found, discard key
    if (cache.includes(value)) return;

    // Store value in our collection
    cache.push(value);
  }
  return value;
});
cache = null; // Enable garbage collection

console.log('Stringified one', stringified);

When we create a circular object it repeats one property again and again which causes the predefined replacer function of JSON.stringify to malfunction and cause Max Call Stack error internally. So, We define a custom replacer function which we can use in order to stringify our object. Removing the Circular Property from object's child. This solution is good if you don't have more children object property. If you want it to work perfectly with children object properties too. Then, You have to add an identifier to your Circular Property. Which you can use as a condition in your custom replacer function.

Check this thread of Circular JSON structure for more information.
Also do check out this blog by mozilla on Cyclic/Circular JSON Structure to learn more about this problem.

0

Circular object have some property, that refers to object itself, that's why it is circular. So it can't be like JSON string:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Print string
// You can see in the result, that circular
// property have **ref** link as it's value
console.log(circular);

So to handle this ref properly you need to introduce your custom logic, which will recreate this instance after you load this string back from localstorage. This is pretty complex and maybe changing your app logic is the better way.

You can flatten regular objects and store them as JSON strings in localstorage, and this is the standard way:

// Regular (non circular) object with key-value structure
const browsers = [
  { name: 'Chrome', company: 'Google' },
  { name: 'Firefox', company: 'Mozilla' },
  { name: 'Safari', company: 'Apple' },
  { name: 'Edge', company: 'Microsoft' }
];

// Stringify to JSON string format
const str = JSON.stringify(browsers);

// Result
console.log(str);

But if you try to do the same thing with circular object, you'll get error:

// Circular object creator
function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Try to JSON.stringify()
const res = JSON.stringify(circular);

** Hack time **
You can try to use third-party libraries for this, like Cycle.js, but this may work unstable and not in all cases... So at your own risk:

function CircularCreator() {
  this.abc = "Hello";
  this.circular = this;
}

// Create circular object
const circular = new CircularCreator();

// Use of Cycle.js lib
const str = JSON.decycle(circular);
const json = JSON.stringify(str);

// Test
console.log(`Stringified and pushed to JSON circular object:`);
console.log(json);

// Here you store it in localstorage
// ...

// Then load back
const loadedStr = JSON.parse(json);

// Then use Cycle.js again
const recreatedCircular = JSON.retrocycle(loadedStr);

// Test
console.log(`Recreated circular object:`);
console.log(recreatedCircular);
<script>
/*
    cycle.js
    2021-05-31

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    This code should be minified before deployment.
    See https://www.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

// The file uses the WeakMap feature of ES6.

/*jslint eval */

/*property
    $ref, decycle, forEach, get, indexOf, isArray, keys, length, push,
    retrocycle, set, stringify, test
*/

if (typeof JSON.decycle !== "function") {
    JSON.decycle = function decycle(object, replacer) {
        "use strict";

// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form

//      {"$ref": PATH}

// where the PATH is a JSONPath string that locates the first occurance.

// So,

//      var a = [];
//      a[0] = a;
//      return JSON.stringify(JSON.decycle(a));

// produces the string '[{"$ref":"$"}]'.

// If a replacer function is provided, then it will be called for each value.
// A replacer function receives a value and returns a replacement value.

// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child element or
// property.

        var objects = new WeakMap();     // object to path mappings

        return (function derez(value, path) {

// The derez function recurses through the object, producing the deep copy.

            var old_path;   // The path of an earlier occurance of value
            var nu;         // The new object or array

// If a replacer function was provided, then call it to get a replacement value.

            if (replacer !== undefined) {
                value = replacer(value);
            }

// typeof null === "object", so go on if this value is really an object but not
// one of the weird builtin objects.

            if (
                typeof value === "object"
                && value !== null
                && !(value instanceof Boolean)
                && !(value instanceof Date)
                && !(value instanceof Number)
                && !(value instanceof RegExp)
                && !(value instanceof String)
            ) {

// If the value is an object or array, look to see if we have already
// encountered it. If so, return a {"$ref":PATH} object. This uses an
// ES6 WeakMap.

                old_path = objects.get(value);
                if (old_path !== undefined) {
                    return {$ref: old_path};
                }

// Otherwise, accumulate the unique value and its path.

                objects.set(value, path);

// If it is an array, replicate the array.

                if (Array.isArray(value)) {
                    nu = [];
                    value.forEach(function (element, i) {
                        nu[i] = derez(element, path + "[" + i + "]");
                    });
                } else {

// If it is an object, replicate the object.

                    nu = {};
                    Object.keys(value).forEach(function (name) {
                        nu[name] = derez(
                            value[name],
                            path + "[" + JSON.stringify(name) + "]"
                        );
                    });
                }
                return nu;
            }
            return value;
        }(object, "$"));
    };
}


if (typeof JSON.retrocycle !== "function") {
    JSON.retrocycle = function retrocycle($) {
        "use strict";

// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
//      {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.

// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.

// So,
//      var s = '[{"$ref":"$"}]';
//      return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.

        var px = /^\$(?:\[(?:\d+|"(?:[^\\"\u0000-\u001f]|\\(?:[\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*")\])*$/;

        (function rez(value) {

// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.

            if (value && typeof value === "object") {
                if (Array.isArray(value)) {
                    value.forEach(function (element, i) {
                        if (typeof element === "object" && element !== null) {
                            var path = element.$ref;
                            if (typeof path === "string" && px.test(path)) {
                                value[i] = eval(path);
                            } else {
                                rez(element);
                            }
                        }
                    });
                } else {
                    Object.keys(value).forEach(function (name) {
                        var item = value[name];
                        if (typeof item === "object" && item !== null) {
                            var path = item.$ref;
                            if (typeof path === "string" && px.test(path)) {
                                value[name] = eval(path);
                            } else {
                                rez(item);
                            }
                        }
                    });
                }
            }
        }($));
        return $;
    };
}

</script>
tarkh
  • 2,424
  • 1
  • 9
  • 12