Turning the Querystring into a JSON object using JavaScript

The query string in the DOM has always been a bit awkward, why there isn’t a standard method of parsing it is beyond me. The normal route most people follow is to convert it in to a simple array of Key/Value pairs. This allows you to then access the values of the query string using the array accessor syntax.

//domain.com/index.html?key=value
var value = querystring_array['key'];

Still a little clumsy isn’t it? Wouldn’t it be great to be able to just retrieve the value from a normal JavaScript/JSON object?

//domain.com/index.html?key=value
var value = querystring.key;

It turns out it’s actually quite easy to do this using the JSON object that is available in all modern browsers.

Getting Started

To actually do this, we still need to turn the query string into and array. There are lots of examples out there, but I prefer this method for its simplicity.

First, we need to get the query string value. We do this using the location object and the search property, then using the slice function we remove the 1st character. The first character is always ‘?’.

location.search.slice(1);

Next, we need to split the query string in to an array, we do this using the split function, passing it the ‘&’ character.

var pairs = location.search.slice(1).split('&');

Now using the the array .forEach function we can iterate through the pairs and split them again, this time using the ‘=’ character. We can then populate our result object, the value at index 0 is the key, and the value is at index 1. We also need to check if the value is actually set, as we could have an empty key on the query string. At this point we should also use the decodeURIComponent function to remove any HTML encoding.

var pairs = location.search.slice(1).split('&');

var result = {};
pairs.forEach(function(pair) {
    pair = pair.split('=');
    result[pair[0]] = decodeURIComponent(pair[1] || '');
});

Converting To JSON

The final step is really easy, all we need to do is use the JSON.stringify method to parse the object, and then call the JSON.parse method to convert it back in to an object.

JSON.parse(JSON.stringify(result));

This final code should look something like this.

function QueryStringToJSON() {            
    var pairs = location.search.slice(1).split('&');
    
    var result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });

    return JSON.parse(JSON.stringify(result));
}

var query_string = QueryStringToJSON();

Now we can easily access the query string values. You can see some examples by following the links below:

Author: Jonny Schnittger
A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio
  • Ramón Ramos

    You could also port the $_GET[] array into a JS function like this:

    function $_GET(a) {
    return (a = location.search.match(RegExp(“[?&]” + a + “=([^&]*)(&?)”, “i”))) ? a[1] : a;
    }

    • Jonny Schnittger

      You could, but as I said I chose the split method for its simplicity. Using a more complex regex every time you want a value, instead of a cached object is nowhere near as performant. It also does does not return a collection, or enable you to use the JSON object which was the point of the snippet.

  • hamnis

    This is not good enough. Query parameters may be repeated, meaning you will replace with the last one if this happens.

    And why would you JSON.parse(JSON.stringify(obj)) ? This makes absolutely no sense.

    • Jonny Schnittger

      JSON.parse(JSON.stringify(obj)) turns the array into a JSON object so you can go
      querystring.key instead of querystring[‘key’].

      Query string values should also not be repeated, they are key value pairs. If you have a requirement for a more complex object, then perhaps the QS is not the correct method of transfer.

      In addition this snippets purpose is to serve as an introduction to the global JSON object and it’s methods, this is why it is not a full tutorial.

      • hamnis

        It is not a question of “should be repeated”, it is what is, and what isn’t true.

        Query params MAY be repeated, meaning your code is WRONG. nothing more, nothing less.

        Since you are already using an object for assignment, assuming all query param characters are legal identifier characters. using foo[“bar”] and foo.bar is equivalent.

        If there are illegal identifier characters, no amount of JSON.parse(JSON.stringify(obj)) will help you.

        • Jonny Schnittger

          You’re missing the point of the snippet, it’s not meant to be a feature complete query string parser that handles all real world scenarios. It’s meant to show in a simple way to someone who is learning JavaScript how to turn the Query string into an array and then turn it into a JSON object.

          You may have years of experience and know all about the various problems that can (and do) occur in the real world. But since this was aimed at someone who has far less experience than you, it is only natural that is to simplistic for you.

          If I wanted a more feature complete parser I could use jQuery and the BBQ plugin function deparam.

  • Imisaninja

    This was really helpful to me. Thanks! :)

  • Map

    This was really helpful to me.

    We will create a lot more new improvement. I’m really looking forward to this. Thanks for the information shared post.

  • 54D0

    Great code, great tutorial and great personality!

  • Abormal Phobic

    This solves multiple parameters of the same name by converting the URL to a proper JSON string.

    function QueryStringToJSON(str) {
    var pairs = str.split(‘&’);
    var result = {};
    pairs.forEach(function(pair) {
    pair = pair.split(‘=’);
    var name = pair[0]
    var value = pair[1]
    if( name.length )
    if (result[name] !== undefined) {
    if (!result[name].push) {
    result[name] = [result[name]];
    }
    result[name].push(value || ”);
    } else {
    result[name] = value || ”;
    }
    });
    return JSON.parse(JSON.stringify(result));
    }