Skip to content

Instantly share code, notes, and snippets.

@kaizhu256
Last active December 10, 2015 19:29
Show Gist options
  • Save kaizhu256/4482049 to your computer and use it in GitHub Desktop.
Save kaizhu256/4482049 to your computer and use it in GitHub Desktop.
javascript - json stringify circular objects in 50 lines of code this code recursively traverses a json array / object. it will stringify all circular objects it encounters for first time and cache their references. that way it can avoid them again in the future.
/*jslint indent: 2, nomen: true, regexp: true, stupid: true*/
(function () {
'use strict';
var circularObject, exports = {};
exports.jsStringifyCircular = function (oo, arr) {
//// stringify circular objects
var ii, kk, out, vv;
arr = arr || [];
if (oo) {
for (ii = 0; ii < arr.length; ii += 1) {
if (oo === arr[ii]) {
oo = '[Circular]';
break;
}
}
}
try {
return JSON.stringify(oo);
} catch (err) {
}
//// fallback
arr.push(oo);
out = '';
//// array
if (Array.isArray(oo)) {
for (ii = 0; ii < oo.length; ii += 1) {
vv = exports.jsStringifyCircular(oo[ii], arr);
if (vv !== undefined) {
out += vv + ',';
}
}
return '[' + (out ? out.slice(0, -1) : out) + ']';
}
//// object
kk = Object.keys(oo).sort();
for (ii = 0; ii < kk.length; ii += 1) {
vv = exports.jsStringifyCircular(oo[kk[ii]], arr);
if (vv !== undefined) {
out += JSON.stringify(kk[ii]) + ':' + vv + ',';
}
}
return '{' + (out ? out.slice(0, -1) : out) + '}';
};
//// test
circularObject = [1, 2, 3, 4];
circularObject.push({'foo': circularObject});
console.log(exports.jsStringifyCircular(circularObject));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment