Don't debug with JSON.Stringify
I’ve been having some problems using JSON.Stringify to inspect objects while debugging inside node.js. It seems like a great choice:
var obj = {
"prop1" : "value1",
"prop2" : 5
}
print(JSON.stringify(obj));
//prints: {"prop1":"value1","prop2":5}
But there are gotchas:
var infinity = 1 / 0;
var func = function() {};
func.innerproperty = "value";
var obj = {
"prop1" : func,
"prop2" : undefined,
"prop3" : infinity
}
print(JSON.stringify(obj);
//prints {"prop3":null}
Oh no! JSON.Stringify has
- ignored
prop1, a function - ignored
func.innerproperty - ignored
prop2, an undefined value - replaced
prop3’sInfinitywithnull.
Yikes! This is because JSON, being a pure data interchange format, has no notation for functions. Or undefined values. And it replaces nonfinite numbers with null.
In node.js, there’s a dedicated function for stringifying objects for debuggings: sys.inspect(object). See the API docs. This fares somewhat better for the last example, outputting:
{
"prop1": [Function],
"prop2": undefined,
"prop3": Infinity
}
EDIT: I opened an issue, and it was fixed in less than a day. Functions with properties are now listed too. Thanks, creationix!
This is pretty important, because it’s very common to use functions as property holders in popular javascript libraries.
- jQuery uses
$both as a selector function, and a library object - underscore.js uses
_as a wrapper function, and a library object