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:

A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio More articles by Jonny Schnittger
Gift cards possess huge potential for merchants who want to increase revenue, acquire new customers and get their brand noticed. It’s generally believed that a gift card program is a marketing tool perfect only for the biggest holiday season or that it can be applied merely by big brands. However, gift cards can be a great tool to drive customers and increase sales, regardless of the season or the brand size. According to the National Retail Federation 2014 survey, 60% (or 6 in 10) of shoppers say...
Introduction ... SCRUD is short for Select, Create, Read, Update and Delete. These are the general actions that any program will perform when working with databases. Yes, there are plenty of ORM applications ( http://en.wikipedia.org/wiki/Object-relational_mapping ) out there that can replace this, but as a general introduction to abstract or generic classes and general development I still think this is worth a read. I should also explain why I have used an abstract class instead of an interface....
Bootstrap 4 is currently the most popular front-end framework in the world. You can use it to build any kind of user interfaces, from admin templates to full-featured websites. In this step-by-step tutorial, we will have a look at how to build a responsive landing page with Bootstrap 4. You can even use it as a homepage or connect it to a specific marketing campaign. The landing page we will build will have five sections: a fixed navigation bar, a hero section, a three-column "Services" section, a full-width...
My team and I recently built an awesome list template on WordPress that ranks a set of Twitter users based on follower count. It allows a content writer to easily add a list of Twitter handles, and generate a well designed post. The first piece of content we created with it generated a 1,212% increase in traffic to our site. Check out the tutorial below if you're interested in building it as well. Requirements ... Input Twitter Handle (required) Name (optional) Tagline (optional) Image (optional) Bio...
Grav is an open source flat-file CMS platform, built by the RocketTheme Team. While there are plenty of great CMS platforms available, they are all mostly database-driven, which can be overkill for smaller websites. Instead of a database, Grav uses folders and a basic file structure, it is focused on speed, simplicity, and flexibility. After reading all of the documentation and spending some time trying Grav out, I’m definitely sold and will be using the platform. I hope you will too. What We’ll...
Videos have been a great way to attract viewers to a website long before YouTube launched back in 2005. But it wasn’t until the release of HTML5 that web developers have had a lightweight solution to playing the video. In the past, displaying a video on your site meant your viewer was required to have a Flash or Java-based player installed on their system in order to watch the video. This was one more thing that would weigh down your site, causing pages to load slower, and be one more thing you’d...
In HTML5 forms got a major upgrade with the addition of some simple, yet flexible validation attributes. To support these added attributes CSS3 also added several new pseudo selectors styling controls based on their validation state. Adding validation ... To illustrate the new attributes and some of the new input types, we'll be building up a simple sign up form. Every sign up form is essentially the same, you fill in your details and click submit. How many times has the form been reset on you after you've...
Continuing on from last weeks introduction to OAuth 2.0 using the Twitter API, this week we're going to focus on an alternate implementation of OAuth 2.0 used in the LinkedIn API. This implementation requires that you manually authorize the application before you can get a token. This implementation is a more complex as it requires you to be re-directed to the authentication server, which then re-directs you back to your own site with the approved token. This allows LinkedIn to add additional permissions...
(追記) (追記ここまで)
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress

AltStyle によって変換されたページ (->オリジナル) /