Skip to content

Instantly share code, notes, and snippets.

@fb55
Created October 29, 2011 11:52
Show Gist options
  • Save fb55/1324362 to your computer and use it in GitHub Desktop.
Save fb55/1324362 to your computer and use it in GitHub Desktop.
(First try of) port of Node.js' util.inspect to JSON.stringify
var inspect = function(obj, showHidden, depth, colors){
var ctx = {
style: /*colors ? stylyze : */function(a){return a;}, //todo
seen: []
};
return formatValue(ctx, obj, 2);
}
var _reName = /(\n\s+)"([A-Za-z_$][\w$]*)"/g;
var _reValue = /\"([^\n]*)\"(?=,?\n)/g;
function formatValue(ctx, obj, intent){
var style = ctx.style;
function format(key, val){
var type = typeof val;
//primitives
switch(type){
case "object":
if(val === null) type = "null";
else switch(Object.prototype.toString.call(val)){
case "[object Date]":
return style(Data.prototype.toUTCString.call(val), "date");
case "[object RegExp]":
return style(RegExp.prototype.toString.call(val), "regexp");
case "[object Error]":
return "[" + Error.prototype.toString.call(val) + "]";
//case "[object Array]":
//case "[object Object]":
default:
if(ctx.seen.indexOf(obj) === -1){
ctx.seen.push(obj);
return val;
} else return style("[Circular]", "special");
}
case "undefined":
case "number":
case "boolean":
return style("" + val, type);
case "string":
val = '\''+String(val).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+'\'';
return style(val, type);
case "function":
return style("[Function" + (val.name && (": " + val.name) ) + "]", "special");
default:
return style(""+val, "special"); //unknown type
}
};
return JSON.stringify(obj, format, intent || 2).replace(_reName, "$1$2").replace(_reValue, "$1");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment