Skip to content

Instantly share code, notes, and snippets.

@frankinedinburgh
Created July 15, 2018 11:10
Show Gist options
  • Save frankinedinburgh/d56dbfb4cf61b091742af3d363f55848 to your computer and use it in GitHub Desktop.
Save frankinedinburgh/d56dbfb4cf61b091742af3d363f55848 to your computer and use it in GitHub Desktop.
convert a query string to a JSON object
export const queryStringToJSON = (query) => {
const setValue = (root, path, value) => {
if (path.length > 1){
const dir = path.shift();
if (typeof root[dir] == 'undefined') {
root[dir] = path[0] === '' ? [] : {};
}
arguments.callee(root[dir], path, value);
} else {
if (root instanceof Array) {
root.push(value);
} else {
root[path] = value;
}
}
};
const nvp = query.split('&');
const data = {};
for (let i of nvp) {
const pair = nvp[i].split('=');
if (!Array.isArray(pair) || pair.length !== 2) {
continue;
}
const name = decodeURIComponent(pair[0]);
const value = decodeURIComponent(pair[1]);
let path = name.match(/(^[^\[]+)(\[.*\]$)?/);
if (!Array.isArray(path) || path.length < 2) {
continue;
}
const first = path[1];
if (path[2]) {
//case of 'array[level1]' || 'array[level1][level2]'
path = path[2].match(/(?=\[(.*)\]$)/)[1].split('][')
} else {
//case of 'name'
path = [];
}
path.unshift(first);
setValue(data, path, value);
}
return data;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment