Last active
October 24, 2015 17:19
-
-
Save bitsmanent/ced160089016e040cd72 to your computer and use it in GitHub Desktop.
Encode an object as a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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