Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active October 24, 2015 17:19
Show Gist options
  • Save bitsmanent/ced160089016e040cd72 to your computer and use it in GitHub Desktop.
Save bitsmanent/ced160089016e040cd72 to your computer and use it in GitHub Desktop.
Encode an object as a string
function serialize(obj, _name) {
var i, pfx, tp, str = [];
if(!obj)
return _name;
tp = typeof obj;
if(obj.length && tp != 'object' && tp != 'string') { /* pure arrays */
for(i = 0; i < obj.length; ++i) {
pfx = (_name ? _name+'['+i+']' : i);
str.push(pfx+'='+obj[i]);
}
}
else { /* objects */
for(i in obj) {
pfx = (_name ? _name+'['+i+']' : i);
if(typeof obj[i] == 'string' || typeof obj[i] == 'number') {
if(obj[i].replace)
str.push(pfx+'='+obj[i].replace(/&/g, '%26'));
else
str.push(pfx+'='+obj[i]);
}
else
str.push(serialize(obj[i], (_name ? _name+'['+i+']' : i)));
}
}
return str.join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment