Deserialize query string to JSON object

Viewed 33291

Tried to find how to make {foo:"bar"} from ?...&foo=bar&... but googled and got only to jQuery.params which does the opposite. Any suggestions please (built-in javascript function, jQuery, Underscore.js - all goes)? Or, do I need to implement it by myself (not a big hassle, just trying not to reinvent the wheel)?

7 Answers

In modern browsers, you can also use Object.fromEntries which makes this even easier.

function queryStringToObject(queryString) {
  const pairs = queryString.substring(1).split('&');
  // → ["foo=bar", "baz=buzz"]

  var array = pairs.map((el) => {
    const parts = el.split('=');
    return parts;
  });
  // → [["foo", "bar"], ["baz", "buzz"]]

  return Object.fromEntries(array);
  // → { "foo": "bar", "baz": "buzz" }
}

console.log(queryStringToObject('?foo=bar&baz=buzz'));


The URLSearchParams interface can Interactive with the browsers URL search parameters. The browser support for URLSearchParams is pretty decent.

For your case, it would be:

console.log(
  Object.fromEntries(new URLSearchParams('foo=bar&baz=buzz'))
);

I know this thread is a bit old - but this is what worked for me - hopefully it will help someone else too ..

var _searchModel = yourquerystring.split("&");
for (var x = 0; x < _searchModel.length; x++) {
  //break each set into key and value pair
  var _kv = _searchModel[x].split("=");

  //console.log(_kv);

  var _fieldID = _kv[0];
  var _fieldVal = _kv[1];
}

Related