thugsb thugsb - 2 years ago 313
Javascript Question query as JSON

Is there a better way to convert a URL's as an object? Maybe just more efficient or trimmed down? I'm using jQuery, but pure JS can work too.

var query =, queryPairs = query.split('&'), queryJSON = {};
$.each(queryPairs, function() { queryJSON[this.split('=')[0]] = this.split('=')[1]; });

Answer Source

Here's a pure JS function. Parses the search part of the current URL and returns an object. (It's a bit verbose for readability, mind.)

function searchToObject() {
  var pairs ="&"),
    obj = {},

  for ( i in pairs ) {
    if ( pairs[i] === "" ) continue;

    pair = pairs[i].split("=");
    obj[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );

  return obj;

On a related note, you're not trying to store the single parameters in "a JSON" but in "an object". ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download