Skip to content

Instantly share code, notes, and snippets.

@alexhawkins
Last active August 29, 2015 14:06
Show Gist options
  • Save alexhawkins/6ede310cfbd9d604db78 to your computer and use it in GitHub Desktop.
Save alexhawkins/6ede310cfbd9d604db78 to your computer and use it in GitHub Desktop.
Hardly Readable JSON.stringify Implementation
var stringifyJSON = function(obj) {
var objElements = [];
//check for literals
if (!(obj instanceof Object))
return typeof obj === 'string' ? '"' + obj + '"' : '' + obj;
//check for arrays
else if (Array.isArray(obj)) {
return '[' + obj.map(function(el) { return stringifyJSON(el); }) + ']';
//check for object if not array
} else if (obj instanceof Object) {
for (var key in obj) {
if (obj[key] instanceof Function)
return '{}';
else
objElements.push('"' + key + '":' + stringifyJSON(obj[key]));
}
return '{' + objElements + '}';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment