Online JSON Tree Viewer Tool – Tutorial

Sam Deering

json-tree-viewer-logo

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.


Online JSON Tree Viewer Tool

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 += '<ul><li><span class="file">' + node + '</span></li></ul>';
        } else {
            return_str += '<ul><li><span class="file">' + node + '</span></li></ul>';
        }
        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 += '<ul><li><span class="folder">' + item + '</span>';
                return_str += JSONTREEVIEWER.processNodes(this);
                return_str += '</li></ul>';
            } 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('<li ')) { /*add the variable name*/
            var val = this.find('span').first().html(); /*Recurse up the DOM*/
            return this.parent().getPath(val + ' > ' + 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(/ &amp;gt; /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.

Download Source

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • Nureal

    great tutorial, Sam.

    I was a bit confused about tree control. How can i get the list is expandable at the first time it load.
    So, i want load only the base of my list.

    • http://jquery4u.com/ jQuery4u

      Hi Nureal, 
      In order to start with the first level of nodes expanded you could call the class state of each root node and set it to “open”. Or simulate the clicking by using trigger or css class swap like so:$(“.file”).removeClass(‘open’).addClass(‘closed’)or$(“.folder”).trigger(‘click’);Thanks,Sam

      • Nureal

        Thanks for the reply, Sam

        It works. :D

  • chaonin guo

    Cool!

  • Lando

    Beautyful

  • de

    i need help whit a json file, some can help me? send me a email to deicide_890@hotmail.com. please