Online JSON Tree Viewer Tool – Tutorial

Sam Deering
Share

I’ve developed a useful Tool plugin that can take in a JSON object and render the data to display in a tree hierarchy. Great for finding the path of nodes in large JSON objects.

Features

  • Enter your JSON either by Uploading a JSON File or Copy and Paste.
  • Expandable tree view.
  • Hover nodes to see the path of the variable.
  • Click to copy the full path of the node.
  • Specify a custom delimiter to the copy node path.

Example Create JSON Tree Calls

If you want to create your own Trees this is how you can create them. JSONTREEVIEWER is the main namespace.

$(function () {
    //Initialise JQUERY4U JSON Tree Viewer
    JSONTREEVIEWER.init();

    //Events to load example files
    $('#example1').bind('click', function () {
        JSONTREEVIEWER.processJSONTree('one-level.json');
    });
});

Main Function to Process JSON Tree

This function determines where to get the JSON from: 1) file upload; or 2) copy and paste; 3) example files.

/*Load the JSON file either by upload or example file and process tree*/
processJSONTree: function (filename) {
    $('#loading').show();
    var data = '',
        branches = '';
    if (filename === 'copyandpastejson') {
        var copypastejson = $('#copyandpastejson').val(); /*validate JSON*/
        if (JSONTREEVIEWER.isValidJSON(copypastejson)) {
            data = copypastejson;
        } else {
            return false;
        }
        if (data === false) {
            return false;
        } /*Build JSON Tree*/
        JSONTREEVIEWER.buildTree(JSONTREEVIEWER.processNodes(jQuery.parseJSON(data)), filename);
    } else {
        //get the JSON file from file upload
        $.ajax({
            type: 'GET',
            url: filename,
            async: false,
            beforeSend: function (x) {
                if (x && x.overrideMimeType) {
                    x.overrideMimeType('application/j-son;charset=UTF-8');
                }
            },
            dataType: 'json',
            success: function (data) { /*Build JSON Tree*/
                JSONTREEVIEWER.buildTree(JSONTREEVIEWER.processNodes(data), filename);
            },
            error: function (e) { /*Invalid JSON*/
                alert('Invalid JSON: ' + e.responseText);
                JSONTREEVIEWER.showErrorMsg();
                return false;
            }
        });
    }
},

Build Tree Function

This function constructs the tree from the branches and displays them on the page.

/*Build JSON Tree*/
buildTree: function (branches, filename) {
    //console.log('branches' + branches);
    if (typeof branches !== 'undefined' || branches !== '') {
        $('#browser').empty().html(branches);
        $('#browser').treeview({
            control: '#treecontrol',
            add: branches
        });
        $('#selected_filename').html('(' + filename + ')');
        $('#loading').hide();
        $('#browser-text').hide();
    } else {
        $('#selected_filename').html('Please select JSON file above...');
        $('#loading').hide();
    }
},

JSON Branch Recursion Function

This function is fairly complex and took a while to code. It basically takes each JSON object recursively, determines is type and creates the HTML for the branches.

/*Process each node by its type (branch or leaf)*/
processNodes: function (node) {
    var return_str = '';
    switch (jQuery.type(node)) {
    case 'string':
        if ($('#hierarchy_chk').is(':checked')) {
            return_str += '
  • ' + node + '
'; } else { return_str += '
  • ' + node + '
'; } break; case 'array': $.each(node, function (item, value) { return_str += JSONTREEVIEWER.processNodes(this); }); break; default: /*object*/ $.each(node, function (item, value) { if ($('#hierarchy_chk').is(':checked')) { return_str += '
  • ' + item + ''; return_str += JSONTREEVIEWER.processNodes(this); return_str += '
'; } else { return_str += JSONTREEVIEWER.processNodes(this); } }); } /*Clean up any undefined elements*/ return_str = return_str.replace('undefined', ''); return return_str; },

Check if JSON is valid

Helper function to check if they JSON is valid and display a message if it’s invalid.

/*Helper function to check if JSON is valid*/
isValidJSON: function (jsonData) {
    try {
        jsonData = jQuery.parseJSON(jsonData);
        //console.log('valid json');
        return true;
    } catch (e) {
        //console.log('invalid json');
        alert(e);
        JSONTREEVIEWER.showErrorMsg();
        return false;
    }
},

Get Path of Node

This function searches the HTML recursively to construct the branch path of a node.

/*jQuery function to create path function used to get the path of the node in the tree*/
jQuery.fn.extend({
    getPath: function (path) { /*The first time this function is called, path won't be defined*/
        if (typeof path == 'undefined') path = ''; /*Add the element name*/
        var cur = this.get(0).nodeName.toLowerCase();
        var id = this.attr('id'); /*Add the #id if there is one*/
        if (typeof id != 'undefined') { /*escape goat*/
            if (id == 'browser') {
                return path;
            }
        }
        var html = this.html();
        if (html.search('
  • ' + path); } else { return this.parent().getPath(path); } } });
  • Events

    A few functions to handle events when a user uploads a JSON file or hovers over the tree.

    /*change event when user changes file upload input*/
    $('#loadfile').live('change', function () {
        JSONTREEVIEWER.processJSONTree($(this).val());
    });
    
    /*store nodepath value to clipboard	(copy to top of page)*/
    $('#browser li').live('click', function () {
        var path = $('#pathtonode').html();
        var pathdelim = $('#pathdelim_chk').val();
        path = path.replace(/ > /g, pathdelim);
        JSONTREEVIEWER.addtoppath(path);
    });
    
    /*mouse IN hover to show path of node*/
    $('#browser li span').live('mouseenter', function () {
        $('#pathtonode').html(JSONTREEVIEWER.getNodePath(this));
        $('#pathtonode').show();
    });
    
    /*mouse OUT hover to show path of node*/
    $('#browser li span').live('mouseleave', function () {
        $('#pathtonode').empty();
        $('#pathtonode').hide();
    });

    Requirements

    I have used the jquery.treeview.async.js plugin to create the expandable tree view.