Skip to content

Instantly share code, notes, and snippets.

@gabrieldewes
Created December 4, 2017 19:41
Show Gist options
  • Save gabrieldewes/a842a577dd5d4b1f9cafaa1a28133493 to your computer and use it in GitHub Desktop.
Save gabrieldewes/a842a577dd5d4b1f9cafaa1a28133493 to your computer and use it in GitHub Desktop.
Parse x-www-form-urlencoded to Json object
function FormURLEncodedToJSON(str) {
"use strict";
var obj, i, pt, keys, j, ev;
if (typeof FormURLEncodedToJSON.br !== 'function') {
FormURLEncodedToJSON.br = function(repl) {
if (repl.indexOf(']') !== -1) {
return repl.replace(/\](.+?)(,|$)/g, function($1, $2, $3) {
return FormURLEncodedToJSON.br( $2 + '}' + $3 );
});
}
return repl;
};
}
str = '{"' + (str.indexOf('%') !== -1 ? decodeURI(str) : str) + '"}';
obj = str.replace(/\=/g,'":"').replace(/&/g,'","').replace(/\[/g,'":{"');
obj = JSON.parse(
obj.replace(/\](.+?)(,|$)/g, function($1,$2,$3) {
return FormURLEncodedToJSON.br( $2 + '}' + $3);
})
);
pt = ('&' + str).replace(/(\[|\]|\=)/g,'"$1"').replace(/\]"+/g,']').replace(/&([^\[\=]+?)(\[|\=)/g,'"&["$1]$2');
pt = (pt + '"').replace(/^"&/,'').split('&');
for (i=0; i<pt.length; i++) {
ev = obj;
keys = pt[i].match(/(?!:(\["))([^"]+?)(?=("\]))/g);
for (j=0; j<keys.length; j++) {
if ( !ev.hasOwnProperty(keys[j])) {
if (keys.length > (j + 1)) {
ev[keys[j]] = {};
}
else {
ev[keys[j]] = pt[i].split('=')[1].replace(/"/g,'');
break;
}
}
ev = ev[keys[j]];
}
}
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment