Skip to content

Instantly share code, notes, and snippets.

@irace
Created January 27, 2012 04:51
Show Gist options
  • Save irace/1687047 to your computer and use it in GitHub Desktop.
Save irace/1687047 to your computer and use it in GitHub Desktop.
Rudimentary object-to-string implementation
function stringify(value) {
if (typeof value === 'string') {
return '"' + value.replace('"', '\"') + '"';
} else if (!value || typeof value !== 'object') {
return value;
}
if (Object.prototype.toString.call(value) === '[object Array]') {
var entries = [];
for (var i = 0; i < value.length; i++) {
entries.push(stringify(value[i]));
}
return '[' + entries.join(',') + ']';
}
var properties = [];
for (var key in value) {
if (value.hasOwnProperty(key) && typeof value[key] !== 'function') {
properties.push('"' + key + '":' + stringify(value[key]));
}
}
return '{' + properties.join(',') + '}';
}
alert(stringify({
firstName: 'Bryan',
lastName: 'Irace',
fullName: function() {
return this.firstName + ' ' + this.lastName;
},
birthday: {
day: 12,
month: 8,
year: 1986
},
languages: ['Java', 'Objective-C', 'JavaScript']
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment