Improved URI to JSON Serializer

Below is an improved version of the URI to JSON serializer JavaScript class I presented a couple of days ago.

What it Does:

uriToJSON() is a tiny JavaScript class, using the HTMLAnchorElement interface to convert URI string into a JSON object.  The object returned by the function contains hash, host, hostname, parameters key-value map, pathname, port and protocol. Works with all major browsers (Firefox, Chrome, Safari, Opera, IE6-10).

What is new:

  • The parameters are no longer in an array but in a hash map, which can be easily accessed like parameters.someParameter rather than parameters[0], parameters[1], etc.
  • Automatic typecasting for strings, Boolean and Numbers for the parameters map and for the port.

Here is the demo, and the code below shows how to use the class:

function uriToJSON(uri) {
    "use strict";

    if(!("hostname" in document.createElement("a"))) {
        return;
    }

    var
        anchor = document.createElement("a"),
        params = {},
        data,
        param;

        anchor.setAttribute("href", uri);
        data = {
            hash: anchor.hash.replace("#", ""),
            host: anchor.host,
            hostname: anchor.hostname,
            parameters: null,
            pathname: anchor.pathname,
            port:  parseInt(anchor.port) ? parseInt(anchor.port) : anchor.port,
            protocol: anchor.protocol,
            uri: uri
        };

        if(anchor.search.split("?")[1]) {
            params = anchor.search.split("?")[1].split("&");
            data.parameters = {};
        }

        for(param in params) {
            if(params.hasOwnProperty) {
                var
                    pair = params[param].split("="),
                    key = pair[0],
                    value = pair[1] === "true" ? true : pair[1] === "false" ? false : pair[1];

                data.parameters[key] = parseInt(value) ? parseInt(value) : value;
            }
        }

        return data;
}

A few tests:

var
    data = uriToJSON("https://www.google.com:3030/search?number1=123&number2=456q=javascript&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a#somehash");

    console.log(data);
    console.log(data.hash);
    console.log(data.host);
    console.log(data.hostname);
    console.log(data.parameters);
    console.log(data.pathname);
    console.log(data.port);
    console.log(data.protocol);
    console.log(data.uri);

Related Posts

15 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>