Skip to content

Instantly share code, notes, and snippets.

@lagden
Created June 29, 2015 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagden/220e5882e09283720141 to your computer and use it in GitHub Desktop.
Save lagden/220e5882e09283720141 to your computer and use it in GitHub Desktop.
query string to javascript object
/* globals console */
'use strict';
function parseQS(str) {
var strArr = String(str)
.replace(/^&/, '')
.replace(/&$/, '')
.split('&');
var sal = strArr.length;
var i;
var j;
var ct;
var p;
var lastObj;
var lastIter;
var undef;
var chr;
var tmp;
var key;
var value;
var postLeftBracketPos;
var keys;
var keysLen;
var obj;
var arr = {};
function fixStr(str) {
return decodeURIComponent(str.replace(/\+/g, '%20'));
}
function isInt(n) {
return Number(n) === n && n % 1 === 0;
}
for (i = 0; i < sal; i++) {
tmp = strArr[i].split('=');
key = fixStr(tmp[0]);
value = (tmp.length < 2) ? '' : fixStr(tmp[1]);
while (key.charAt(0) === ' ') {
key = key.slice(1);
}
if (key.indexOf('\x00') > -1) {
key = key.slice(0, key.indexOf('\x00'));
}
if (key && key.charAt(0) !== '[') {
keys = [];
postLeftBracketPos = 0;
for (j = 0; j < key.length; j++) {
if (key.charAt(j) === '[' && !postLeftBracketPos) {
postLeftBracketPos = j + 1;
} else if (key.charAt(j) === ']') {
if (postLeftBracketPos) {
if (!keys.length) {
keys.push(key.slice(0, postLeftBracketPos - 1));
}
keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
postLeftBracketPos = 0;
if (key.charAt(j + 1) !== '[') {
break;
}
}
}
}
if (!keys.length) {
keys = [key];
}
for (j = 0; j < keys[0].length; j++) {
chr = keys[0].charAt(j);
if (chr === ' ' || chr === '.' || chr === '[') {
keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1);
}
if (chr === '[') {
break;
}
}
obj = arr;
for (j = 0, keysLen = keys.length; j < keysLen; j++) {
key = keys[j]
.replace(/^['"]/, '')
.replace(/['"]$/, '');
lastIter = j !== keys.length - 1;
lastObj = obj;
if ((key !== '' && key !== ' ') || j === 0) {
if (obj[key] === undef) {
obj[key] = isInt(key - '') ? {} : [];
}
obj = obj[key];
} else {
ct = -1;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
if (+p > ct && p.match(/^\d+$/g)) {
ct = +p;
}
}
}
key = ct + 1;
}
}
lastObj[key] = value;
}
}
return arr;
}
var j1 = parseQS('a=123&b[0][c]=c1&b[1][d]=d1');
var j2 = parseQS('a=123&b%5B0%5D%5Bc%5D=c1&b%5B1%5D%5Bd%5D=d1');
console.log(j1); // { a: '123', b: [ { c: 'c1' }, { d: 'd1' } ] }
console.log(j2); // { a: '123', b: [ { c: 'c1' }, { d: 'd1' } ] }
console.log(j1.b[0].c); // c1
console.log(j2.b[1].d); // d1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment