JSON Visualizse

Visualize JSON

by ExplosionPIlls

HTML

{
"about": "about",
"episodes": [
    {
        "id": 123,
        "title": "the title",
        "pod": {
            "podtitle": "podtitle",
            "url": "url"
        }
    },
    {
        "id": 1234,
        "title": "the title2",
        "pod": {
            "podtitle": "podtitle2",
            "url": "url2"
        }
}
]}

CSS

.structure {
    color: red;
    display: inline-block;
}
.name {
    color: green;
    display: inline-block;
    margin-right: .5em;
}
.object-content, .array-content {
    color: blue;
    display: inline-block;
}
.comma {
    color: red;
    display: inline-block;
}
body {
    font-family: monospace;
}

JavaScript

JsonVisualize = function (obj, container) {
    if (typeof obj === 'string') {
        obj = JSON.parse(obj);
    }
    this.obj = obj;
    this.title = 'objectVariableName';
    this.depth = 0;
    this.container = container;
    this.elementClass = 'object-content';
    this.startLoop = false;
};

JsonVisualize.prototype = {
    display: function () {
        this.recur(this.obj);
    },

    recur: function (element) {
        if (this.isArray(element)) {
            this.displayArray(element);
        }
        else if (element === null) {
            this.displayItem(element);
        }
        else if (typeof element === 'object') {
            this.displayObject(element);
        }
        else {
            this.displayItem(element);
        }
    },

    displayArray: function (element) {
        this.create('[', 'structure');
        this.br();
        var originalTitle = this.title;
        this.depth++;
        this.elementClass = 'array-content';
        this.startLoop = false;
        for (var x = 0; x < element.length; x++) {
            this.title = originalTitle + '[' + x + ']';
            this.recur(element[x]);
            if (x !== element.length - 1) {
                this.create(',', 'comma');
            }
            this.br();
        }
        this.depth--;
        this.title = originalTitle;
        this.create(']', 'structure');
    },

    displayItem: function (element) {
        this.create(element, this.elementClass, this.title);
    },

    displayObject: function (element) {
        var originalTitle = this.title;
        this.create('{', 'structure');
        this.br();
        this.depth++;
        this.elementClass = 'object-content';
        for (var item in element) {
            if (element.hasOwnProperty(item)) {
                //This is much more restrictive than an actual valid variable name,
                //but the bracket syntax works regardless
                if (!/^[a-z$_][a-z$_0-9]*$/i.test(item)) {
           ...