Recursive JSON to URL function

Posted on by Alex in Randomness, Software

While working on a snazzy new toy for Velocity, I needed a script to transform JSON to URL parameters. I found this clever method for doing it, but sadly, it wasn’t recursive, so it would only generate URL parameters for the first level of JSON elements.

I rewrote the function to recurse over all elements in the object tree and spit them out in a URL-safe string.

  var JSON = {
    params : function(a1){
      var u=[];
      for(x in a1){
        if(a1[x] instanceof Array)
          u.push(x+"="+encodeURI(a1[x].join(",")));
        else if(a1[x] instanceof Object)
          u.push(JSON.params(a1[x]));
        else
          u.push(x+"="+encodeURI(a1[x]));
      }
      return u.join("&");
    }
  };
var doc = {
  "env":{
    "platform":"linux",
    "browser":"Firefox%2F3.5.8"
  },
  "query":{
    "project":"user-tracking",
    "fetch_time":"0"
  },
  "user":{
    "locale":"en-US",
    "cluster":""
  },
  "last_modified":"1270872812"
};

Leave a Reply

You must be logged in to post a comment.