I was recently tasked at my job to write some Javascript to pass a request for a static page and tack on some key-value pairs using the traditional HTTP query string (QS) method…
ie. http://www.mysite.com/index.html?foo=bar&baz=bim
Pretty trivial, until I realized that one of the pairs could potentially contain a value which would break the Javascript QS parsing that I was doing…
ie: index.html?foo=bar&baz=http://www.yoursite.com/default.htm?foo=bim
So, what to do? Write some convoluted parsing algorithms to account for multiple nested QS’s contained by the value I was dynamically passing? I almost, went down that road until a colleague of mine said “why not use JSON”. A-hah! very good point! Lets explore what that would entail and the benefits of doing so…
For example here are the key/values we want to pass to another page:
- userName = ‘John Pencola’
- id = 12345
- url = ‘http://www.johnpencola.com/index.html?id=23&tabindex=6′
As you can see, using a traditional querystring key/val approach gets messy here…
[html]
http://blog.johnpencola.com/form.php?userName=John Pencola&id=12345&url=http://www.johnpencola.com/index.html?id=23&tabindex=6
[/html]
Not only are the question marks harder to deal with, but the key for ‘id’ is duplicated which poses additional logical decisions in the parser code that would need to handle this string.
Here is the JSON way of doing it…
[js]
var params = {‘userName’:'John Pencola’, ‘id’:’12345′, ‘url’:'http://www.johnpencola.com/index.html?id=23&tabindex=6′}
[/js]
Your new URL would then look like this…
[html]
src=’index.html&myParams=’+params
[/html]
That’s more like it! Now we have an anonymous object that is storing the key-val pairs in an organized and easy to access manner. So, now lets have a look at the parsing that is needed to extract those values…
[js]
function parseQueryString() {
var uri = document.location.href;
var paramStr = uri.split(‘myParams=’)[1];
var params = paramStr.substr(paramStr.indexOf(“{“),(paramStr.indexOf(“}”)+1));
var jsonObj = eval(“(“+params+”)”);
}
[/js]
Now you can interrogate that JSON object in the typical dot notation manner accessing that object…
[js]
alert(jsonObj.userName)
// alerts : John Pencola
[/js]
So what does this approach buy us v. the traditional way?
- It’s ‘cleaner’ to look at in my opinion. Parameters can be logically grouped and named in a human readable way.
- Multiple JSON objects can be concatenated and can then contain duplicate key definitions while still remaining independent.
- Allows for the use of SGML compliant URI’s (Based on the W3C recommendation to avoid using ‘&’ in the QS).
- Way easier to pluck values and work with as a native Javascript object.
Well, thats it! Hope this sparks some new ideas and thanks to Allan for suggesting this!
