Skip to content

Instantly share code, notes, and snippets.

@ptekchand
Created August 24, 2012 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ptekchand/3447280 to your computer and use it in GitHub Desktop.
Save ptekchand/3447280 to your computer and use it in GitHub Desktop.
Hack to work around "TypeError: Converting circular structure to JSON"
/**
* Hack to work around "TypeError: Converting circular structure to JSON"
* which is seen when using JSON.stringify
* Intended to inspection/debugging purposes.
* Note: Will not display an Array in square brackets.
* Shows extra trailing comma before closing brace.
* @param obj
* @param [onlyProps] - Show only property names
* @param {String[]} [skipTypes=['function']] - array of types to trace only the type instead of value.
* @return {String}
*/
function shallowStringify(obj, onlyProps, skipTypes) {
var objType = typeof(obj);
if(['function', 'undefined'].indexOf(objType)>=0) {
return objType;
} else if(['string', 'number', 'boolean'].indexOf(objType)>=0) {
return obj; // will toString
}
// objType == 'object'
var res = '{';
for (p in obj) { // property in object
if(typeof(onlyProps)!=='undefined' && onlyProps) {
// Only show property names as values may show too much noise.
// After this you can trace more specific properties to debug
res += p+', ';
} else {
var valType = typeof(obj[p]);
if(typeof(skipTypes)=='undefined') {
skipTypes = ['function'];
}
if(skipTypes.indexOf(valType)>=0) {
res += p+': '+valType+', ';
} else {
res += p+': '+obj[p]+', ';
}
}
}
res += '}';
return res;
}
// Tests:
function ssTests() {
console.log('shallowStringify string: '+shallowStringify('TestString'));
console.log('shallowStringify number: '+shallowStringify(42));
console.log('shallowStringify boolean: '+shallowStringify(true));
console.log('shallowStringify Array: '+shallowStringify(['TestString', 42, true]));
//console.log('net.createServer\'s socket: '+shallowStringify(socket));
//console.log('net.createServer\'s socket: '+shallowStringify(socket, false, []));
}
@mhjadav
Copy link

mhjadav commented Jul 1, 2016

This function is not return proper value if object contains another object inside-
return value of this function is - "{init: function, Helpers: [object Object], CurrentState: [object Object], CurrentStateHelpers: [object Object], MeetingController: [object Object], Libraries: [object Object], Diagnostic: [object Object], registerModules: function, CSS: [object Object], PluginInterface: function, FBPluginInterface: function, NACLPluginInterface: function, NACLControlChannel: function, WebRTC: [object Object], meaCoreInited: true, VideoInstance: [object Object], }"

Actually it should not be like that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment