LinuxMeerkat

I swear! Meerkats can do Linux


Leave a comment

Converting a URL string into Json

I was making a website the other day and I wanted to somehow pass variables that can be read with javascript. So if the user browsed to
http://www.example.com?height=100px&width=50px, the variables height and width should be read from javascript. Note that this method of passing the variables in the URL is used most notably for CGI, aka server-side scripting(PHP anyone?).

JSON

So I was a bit puzzled while looking around at stackoverflow as many people do think that there is something magical about Json. Json is nothing more than a standard on how things are stored. The standard pretty much sums up to this:

  1. Variables are stored as varName = value
  2. Arrays are stored as arrayName = [value1, value2, value3 .. ]
  3. A value can be: a number, a string, true, false, none
  4. The whole thing is encapsulated in wavy braces

For my example, the Json structure(after parsing the URL string) should look like this:

{
   "height": "100px"
   "width" : "50px"
}

In this case the values are strings. Keep in mind however that according to the standard, they could be anything between a number, a string, true, false and none.

My parser

So to get this structure from the URL, I needed some kind of parsing. All the solutions I found either used regular expressions, or they wanted a whole library to be imported, or just didn’t support arrays. So I made up my own ugly solution.

The function url2json() uses pure JavaScript code which doesn’t use regular expressions and accepts both arrays and variables:

function url2json(url) {
   var obj={};

   function arr_vals(arr){
      if (arr.indexOf(',') > 1){
         var vals = arr.slice(1, -1).split(',');
         var arr = [];
         for (var i = 0; i < vals.length; i++)
            arr[i]=vals[i];
         return arr;
      }
      else
         return arr.slice(1, -1);
   }

   function eval_var(avar){
      if (avar[1].indexOf('[') == 0)
         obj[avar[0]] = arr_vals(avar[1]);
      else
         obj[avar[0]] = avar[1];
   }

   if (url.indexOf('?') > -1){
      var params = url.split('?')[1];
      if(params.indexOf('&') > 2){
         var vars = params.split('&');
         for (var i in vars)
            eval_var(vars[i].split('='));
      }
      else
         eval_var(params.split('='));
   }

   return obj;
}

To keep things clean, all values are parsed into strings. As the input of the function is a string it just makes sense to give back strings so no extra processing takes place if it’s not needed(checking if every value is of a certain type). It’s up to the user to convert the strings into numbers or whatever they want, if they really have to.

Parsing variables

To use the function with the example above, I would just run

obj = url2json("http://www.example.com?height=100px&amp;width=50px
");
console.log(obj.height);
console.log(obj.width);

Launching the console in the browser(CTRL+SHIFT+K), we get the results:

"100px"
"50px"

Parsing arrays

Arrays are parsed like this

obj = url2json("www.x.com?numbers=[100,45,88,90]&mixed=[red,56,blue,20]");
console.log(obj);

The object logged in the console looks like this:

{
   "numbers" : ["100", "45", "88", "90"]
   "mixed" : ["red", "56", "blue", "20"]
}


10 Comments

Headless mp3 player

I am working on a greasemonkey script where I want to be able and play mp3 files in the background. The <audio> tag would be a good and easy solution but unfortunately Firefox doesn’t support mp3 playback because of license issues.

With headless we mean gui-less. So I was looking for a dummy mp3 player that would just do the playback while all the control would be javascript driven.

I found in the end this simple .swf file here that supports the follow:

  • Play
  • Pause
  • Stop
  • Loop on/off

The problem I faced, as usual, was zero documentation. Although the source code of the mp3 player is available, it was hard for me to decode how to use the player, especially when I am totally unfamiliar with actionscript.

In the end I managed and in fact I made two minimal templates to help out future users.

Steps

  1. Download this package. Alternative links: on 2shared, on speedyshare
  2. Unpack to your server.
  3. Browse to index.html or index2.html

Scenario 1

index.html uses inline javascript inside the html code to control the mp3 player. In particular it makes normal <a> tags that once clicked send a query to the mp3player.swf:

<a href="javascript:mp3player.playSound('song.mp3')">Play</a>
<a href="javascript:mp3player.pauseSound()">Pause</a>
<a href="javascript:mp3player.stopSound()">Stop</a>
<a href="javascript:mp3player.loopOn()">Loop On</a>
<a href="javascript:mp3player.loopOff()">Loop Off</a>

This is the fast dirty way to get things work without using an external javascript file.

Scenario 2

Index.html2 loads an external javascript file which in this case is controlplayer.js. This is much more flexible and lets you add advanced behaviour from inside the javascript file.

As you notice the html code is as simple as this

<button id="playButton">Play</button>
<button id="pauseButton">Pause</button>
<button id="stopButton">Stop</button>
<button id="loopOnButton">Loop On</button>
<button id="loopOffButton">Loop Off</button>

the key elements in this segment are the ids. As long as the ids are not changed you are free to change the tag type as you wish. For example

<h1 id="playButton">Play</h1>
<p id="pauseButton">Pause</p>
<div id="stopButton">Stop</div>
<p id="loopOnButton">Loop On</p>
<a href="javascript:return" id="loopOffButton">Loop Off</a>

does work as good as the previous code without breaking any functionality.

NOTICE: If controlling the playback doesn’t work once you unzipped, make sure that the files are on your website folder. Launching the .html files directly from a local folder(for example “desktop”) will not work. That is due to security reasons when it comes to flash.