Convert a Javascript Dictionary To GET URL Parameters

I've had serveral instances in the recent past where I needed to take a javascript dictionary and convert it into a set of GET parameters to be used in a URI. Usually this happens when I'm building an AJAX request.

Anyway, since I've used this function over and over I thought I'd post it incase it helps any of you Googling for something similar. Here's the function...

function dictToURI(dict) {
  var str = [];
  for(var p in dict){
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(dict[p]));
  }
  return str.join("&");
}

You might use it in a case like this...

var myKeyValues = {
  "key1" : "value1",
  "key2" : "value2",
  "key3" : "value3"
}

var ajaxURL = "http://api.mattcrampton.com/xyz?" + dictToURI(myKeyValues);

Which sets ajaxURL to...

http://api.mattcrampton.com/xyz?key1=value1&key2=value2&key3=value3

P.S. If you're pushing this to a static hosted site on S3, be sure to read my post on Cloudfront Invalidation

See all blog posts or go back to Matt Crampton

Other Blog Posts

Invalidating all files from a Cloudfront distribution cache from the command line

As I mentioned before, this website is built using Jekyll which generates static html which is then hosted on AWS S3. This works great for... Read more...

Checking if a variable is set in Jekyll

This site is built using Jekyll which allows me to generate the entire thing as static html which can then be hosted on AWS S3.... Read more...

Query an NTP server from Python

I came across a need to query an NTP server to get the current time from a python script. There are some great python modules... Read more...
See All Blog Posts