Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Created March 24, 2013 15:11
Show Gist options
  • Save nimamehanian/5232288 to your computer and use it in GitHub Desktop.
Save nimamehanian/5232288 to your computer and use it in GitHub Desktop.
Recursive implementation of JSON.stringify
var stringifyJSON = function(object){
// Base case: If not object and is a string,
// wrap in quotes and return.
// If not passed in (i.e., null),
// return empty string.
if(typeof object !== 'object' || object === null){
if(typeof object === 'string'){
object = '"' + object + '"';
}
return String(object);
} else {
// If object or array:
var property = [];
var value = [];
var json = [];
// Boolean that's toggling whether an array is passed in.
var array = (object && object.constructor === Array);
// For each key/value pair, if value is a string,
// wrap in quotes and reassign. However,
// if value is present and is, itself, an object,
// recall function and pass it value (because it's an object).
for(property in object){
value = object[property];
if(typeof value === 'string'){
value = addEscapeChars(value);
value = '"' + value + '"';
} else if(typeof value === 'function' || typeof value === 'undefined'){
delete object[property];
return stringifyJSON(object);
} else if(typeof value === 'object' && value !== null){
value = stringifyJSON(value);
}
json.push((array ? '' : '"' + property + '":') + String(value));
}
// Wrap in appropriate bracket type and return.
return (array ? '[' : '{') + String(json) + (array ? ']' : '}');
}
};
var addEscapeChars = function(string){
var result = [];
var chars = string.split('');
for(var i = 0, len = chars.length; i < len; i++){
if(chars[i] === String.fromCharCode(34) ||
chars[i] === String.fromCharCode(92) ){
result.push(String.fromCharCode(92));
result.push(chars[i]);
} else {
result.push(chars[i]);
}
}
return result.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment