Improved URI to JSON Serializer

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

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:

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

[sourcecode language=”javascript”]
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;
}
[/sourcecode]

A few tests:

[sourcecode language=”javascript”]
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);
[/sourcecode]

Related Posts

Categories and Tags
Links

© 2006 - 2018 Martin Ivanov