HTML5, CSS3 & JS Experiments

By Martin Ivanov

URI to JSON Serializer

Register the Class

<script src="uriToJSON.js"></script>

Usage and Code Insight

var
    data = window.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);
/*
 * uriToJSON
 * URI to JSON Serializer JavaScript Class
 * developer's website: http://wemakesites.net/#!/web-dev
 * developer's twitter: https://twitter.com/#!/wemakesitesnet
 * developer's blog http://acidmartin.wordpress.com/
 **/
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;
}