Skip to content

Instantly share code, notes, and snippets.

@brakmic
Last active July 31, 2017 12:22
Show Gist options
  • Save brakmic/5b961f5a40ec10a42b5d to your computer and use it in GitHub Desktop.
Save brakmic/5b961f5a40ec10a42b5d to your computer and use it in GitHub Desktop.
AngularJS-Module: Stringify JSON Objects with circular dependencies
(function () {
/* converted by @brakmic */
/* original code: https://github.com/isaacs/json-stringify-safe */
/* usage example:
*
*angular.module("myModule", ['jsonStringify'])
* .controller("MainCtrl", ['StringifyJsonService', MainCtrl]);
*
*function MainCtrl(StringifyJsonService){
* var vm = this;
* vm.myCircularJson = { /* values, values, values */ };
/* vm.stringifyCircularJson = stringifyCircularJson;
*
* function stringifyCircularJson(circularJson){
* console.log(StringifyJsonService.stringify(circularJson));
* }
* }
*
* Example:
*
* <div ng-controller="MainCtrl as vm">
*
* <input type="text" ng-model="vm.myCircularJson"/>
* <div ng-bind="vm.myCircularJson"></div>
* <div ng-bind="vm.stringifyCircularJson(vm.myCircularJson)"></div>
*
* </div> */
angular.module('jsonStringify', [])
.factory('StringifyJsonService', StringifyJsonServiceFactory);
function StringifyJsonServiceFactory() {
var service = {};
function getSerialize(fn, decycle) {
var seen = [], keys = [];
decycle = decycle || function (key, value) {
return '[Circular ' + getPath(value, seen, keys) + ']'
};
return function (key, value) {
var ret = value;
if (typeof value === 'object' && value) {
if (seen.indexOf(value) !== -1)
ret = decycle(key, value);
else {
seen.push(value);
keys.push(key);
}
}
if (fn) ret = fn(key, ret);
return ret;
}
}
function getPath(value, seen, keys) {
var index = seen.indexOf(value);
var path = [keys[index]];
for (index--; index >= 0; index--) {
if (seen[index][path[0]] === value) {
value = seen[index];
path.unshift(keys[index]);
}
}
return '~' + path.join('.');
}
service.stringify = function(obj, fn, spaces, decycle) {
return JSON.stringify(obj, getSerialize(fn, decycle), spaces);
}
service.stringify.getSerialize = getSerialize;
return service;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment