JSFiddle - React, Tailwind, and code Playground

by dshilkret

HTML

<div id="container"></div>

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;
}
#container {
    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.title = originalTitle + '.' + item;
                this.startLoop = true;
                this.create('"' + item + '":', 'name');
                this.recur(element[item]);
            }
   ...