[javascript] Convert JSON array to an HTML table in jQuery

Is there a really easy way I can take an array of JSON objects and turn it into an HTML table, excluding a few fields? Or am I going to have to do this manually?

This question is related to javascript jquery json ajax html-table

The answer is


Make a HTML Table from a JSON array of Objects by extending $ as shown below

$.makeTable = function (mydata) {
    var table = $('<table border=1>');
    var tblHeader = "<tr>";
    for (var k in mydata[0]) tblHeader += "<th>" + k + "</th>";
    tblHeader += "</tr>";
    $(tblHeader).appendTo(table);
    $.each(mydata, function (index, value) {
        var TableRow = "<tr>";
        $.each(value, function (key, val) {
            TableRow += "<td>" + val + "</td>";
        });
        TableRow += "</tr>";
        $(table).append(TableRow);
    });
    return ($(table));
};

and use as follows:

var mydata = eval(jdata);
var table = $.makeTable(mydata);
$(table).appendTo("#TableCont");

where TableCont is some div


Converting a 2D JavaScript array to an HTML table

To turn a 2D JavaScript array into an HTML table, you really need but a little bit of code :

_x000D_
_x000D_
function arrayToTable(tableData) {_x000D_
    var table = $('<table></table>');_x000D_
    $(tableData).each(function (i, rowData) {_x000D_
        var row = $('<tr></tr>');_x000D_
        $(rowData).each(function (j, cellData) {_x000D_
            row.append($('<td>'+cellData+'</td>'));_x000D_
        });_x000D_
        table.append(row);_x000D_
    });_x000D_
    return table;_x000D_
}_x000D_
_x000D_
$('body').append(arrayToTable([_x000D_
    ["John","Slegers",34],_x000D_
    ["Tom","Stevens",25],_x000D_
    ["An","Davies",28],_x000D_
    ["Miet","Hansen",42],_x000D_
    ["Eli","Morris",18]_x000D_
]));
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Loading a JSON file

If you want to load your 2D array from a JSON file, you'll also need a little bit of Ajax code :

$.ajax({
    type: "GET",
    url: "data.json",
    dataType: 'json',
    success: function (data) {
        $('body').append(arrayToTable(data));
    }
});

Using jQuery will make this simpler.

The following code will take an array of arrays and store convert them into rows and cells.

$.getJSON(url , function(data) {
    var tbl_body = "";
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = "";
        $.each(this, function(k , v) {
            tbl_row += "<td>"+v+"</td>";
        });
        tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
        odd_even = !odd_even;               
    });
    $("#target_table_id tbody").html(tbl_body);
});

You could add a check for the keys you want to exclude by adding something like

var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };

at the start of the getJSON callback function and adding:

if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}

around the tbl_row += line.

Edit: Was assigning a null variable previously

Edit: Version based on Timmmm's injection-free contribution.

$.getJSON(url , function(data) {
    var tbl_body = document.createElement("tbody");
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = tbl_body.insertRow();
        tbl_row.className = odd_even ? "odd" : "even";
        $.each(this, function(k , v) {
            var cell = tbl_row.insertCell();
            cell.appendChild(document.createTextNode(v.toString()));
        });        
        odd_even = !odd_even;               
    });
    $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild
});

Modified a bit code of @Dr.sai 's code. Hope this will be useful.

(function ($) {
    /**
     * data - array of record
     * hidecolumns, array of fields to hide
     * usage : $("selector").generateTable(json, ['field1', 'field5']);
     */
    'use strict';
    $.fn.generateTable = function (data, hidecolumns) {
        if ($.isArray(data) === false) {
            console.log('Invalid Data');
            return;
        }
        var container = $(this),
            table = $('<table>'),
            tableHead = $('<thead>'),       
            tableBody = $('<tbody>'),       
            tblHeaderRow = $('<tr>');       

        $.each(data, function (index, value) {
            var tableRow = $('<tr>').addClass(index%2 === 0 ? 'even' : 'odd');      
            $.each(value, function (key, val) {
                if (index == 0 && $.inArray(key, hidecolumns) <= -1 ) { 
                    var theaddata = $('<th>').text(key);
                    tblHeaderRow.append(theaddata); 
                }
                if ($.inArray(key, hidecolumns) <= -1 ) { 
                    var tbodydata = $('<td>').text(val);
                    tableRow.append(tbodydata);     
                }
            });
            $(tableBody).append(tableRow);  
        });
        $(tblHeaderRow).appendTo(tableHead);
        tableHead.appendTo(table);      
        tableBody.appendTo(table);
        $(this).append(table);    
        return this;
    };
})(jQuery);

Hoping this will be helpful to hide some columns too. Link to file


You could use a jQuery plugin that accepts JSON data to fill a table. jsonTable


I found a duplicate over here: Convert json data to a html table

Well, there are many plugins exists, including commercial one (Make this as commercial project?! Kinda overdone... but you can checkout over here: https://github.com/alfajango/jquery-dynatable)

This one has more fork: https://github.com/afshinm/Json-to-HTML-Table

//Example data, Object 
var objectArray = [{
    "Total": "34",
    "Version": "1.0.4",
    "Office": "New York"
}, {
    "Total": "67",
    "Version": "1.1.0",
    "Office": "Paris"
}];

//Example data, Array
var stringArray = ["New York", "Berlin", "Paris", "Marrakech", "Moscow"];

//Example data, nested Object. This data will create nested table also.
var nestedTable = [{
    key1: "val1",
    key2: "val2",
    key3: {
        tableId: "tblIdNested1",
        tableClassName: "clsNested",
        linkText: "Download",
        data: [{
            subkey1: "subval1",
            subkey2: "subval2",
            subkey3: "subval3"
        }]
    }
}];

Apply the code

//Only first parameter is required
var jsonHtmlTable = ConvertJsonToTable(objectArray, 'jsonTable', null, 'Download');

Or you might want to checkout this jQuery plugins as well: https://github.com/jongha/jquery-jsontotable

I think jongha's plugins is easier to use

<div id="jsontotable" class="jsontotable"></div>

var data = [[1, 2, 3], [1, 2, 3]];
$.jsontotable(data, { id: '#jsontotable', header: false });

If you accept using another jQuery dependent tool, I would recommend using Tabulator. Then you will not need to write HTML or any other DOM generating code, while maintaining great flexibility regarding the formatting and processing of the table data.

enter image description here

For another working example using Node, you can look at the MMM-Tabulator demo project.


with pure jquery:

window.jQuery.ajax({
    type: "POST",
    url: ajaxUrl,
    contentType: 'application/json',
    success: function (data) {

        var odd_even = false;
        var response = JSON.parse(data);

        var head = "<thead class='thead-inverse'><tr>";
        $.each(response[0], function (k, v) {
            head = head + "<th scope='row'>" + k.toString() + "</th>";
        })
        head = head + "</thead></tr>";
        $(table).append(head);//append header
       var body="<tbody><tr>";
        $.each(response, function () {
            body=body+"<tr>";
            $.each(this, function (k, v) {
                body=body +"<td>"+v.toString()+"</td>";                                        
            }) 
            body=body+"</tr>";               
        })
        body=body +"</tbody>";
        $(table).append(body);//append body
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.responsetext);
    }
});

A still shorter way

$.makeTable = function (mydata) {
            if (mydata.length <= 0) return "";
           return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
                return "<th>" + key + "</th>";
            }).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
                return "<tr>" + $.map(index, function (val, key) {
                    return "<td>" + val + "</td>";
                }).join("\n") + "</tr>";
            }).join("\n"));
        };

You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!

_x000D_
_x000D_
//Sample JSON 2D array_x000D_
var json = [{_x000D_
  "Total": "34",_x000D_
  "Version": "1.0.4",_x000D_
  "Office": "New York"_x000D_
}, {_x000D_
  "Total": "67",_x000D_
  "Version": "1.1.0",_x000D_
  "Office": "Paris"_x000D_
}];_x000D_
_x000D_
// Get Table headers and print_x000D_
for (var k = 0; k < Object.keys(json[0]).length; k++) {_x000D_
  $('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');_x000D_
}_x000D_
_x000D_
// Get table body and print_x000D_
for (var i = 0; i < Object.keys(json).length; i++) {_x000D_
  $('#table_content').append('<tr>');_x000D_
  for (var j = 0; j < Object.keys(json[0]).length; j++) {_x000D_
    $('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');_x000D_
  }_x000D_
  $('#table_content').append('</tr>');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr id="table_head">_x000D_
_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody id="table_content">_x000D_
_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_


Pure HTML way, not vulnerable like the others AFAIK:

// Function to create a table as a child of el.
// data must be an array of arrays (outer array is rows).
function tableCreate(el, data)
{
    var tbl  = document.createElement("table");
    tbl.style.width  = "70%";

    for (var i = 0; i < data.length; ++i)
    {
        var tr = tbl.insertRow();
        for(var j = 0; j < data[i].length; ++j)
        {
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i][j].toString()));
        }
    }
    el.appendChild(tbl);
}

Example usage:

$.post("/whatever", { somedata: "test" }, null, "json")
.done(function(data) {
    rows = [];
    for (var i = 0; i < data.Results.length; ++i)
    {
        cells = [];
        cells.push(data.Results[i].A);
        cells.push(data.Results[i].B);
        rows.push(cells);
    }
    tableCreate($("#results")[0], rows);
});

Pivoted single-row view with headers on the left based on @Dr.sai's answer above.

Injection prevented by jQuery's .text method

$.makeTable = function (mydata) {
    var table = $('<table>');
    $.each(mydata, function (index, value) {
        // console.log('index '+index+' value '+value);
        $(table).append($('<tr>'));
        $(table).append($('<th>').text(index));
        $(table).append($('<td>').text(value));
    });
    return ($(table));
};

One simple way of doing this is:

_x000D_
_x000D_
var data = [{_x000D_
  "Total": 34,_x000D_
  "Version": "1.0.4",_x000D_
  "Office": "New York"_x000D_
}, {_x000D_
  "Total": 67,_x000D_
  "Version": "1.1.0",_x000D_
  "Office": "Paris"_x000D_
}];_x000D_
_x000D_
drawTable(data);_x000D_
_x000D_
function drawTable(data) {_x000D_
_x000D_
  // Get Table headers and print_x000D_
  var head = $("<tr />")_x000D_
  $("#DataTable").append(head);_x000D_
  for (var j = 0; j < Object.keys(data[0]).length; j++) {_x000D_
    head.append($("<th>" + Object.keys(data[0])[j] + "</th>"));_x000D_
  }_x000D_
_x000D_
  // Print the content of rows in DataTable_x000D_
  for (var i = 0; i < data.length; i++) {_x000D_
    drawRow(data[i]);_x000D_
  }_x000D_
_x000D_
}_x000D_
_x000D_
function drawRow(rowData) {_x000D_
  var row = $("<tr />")_x000D_
  $("#DataTable").append(row);_x000D_
  row.append($("<td>" + rowData["Total"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Version"] + "</td>"));_x000D_
  row.append($("<td>" + rowData["Office"] + "</td>"));_x000D_
}
_x000D_
table {_x000D_
  border: 1px solid #666;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th {_x000D_
  background: #f8f8f8;_x000D_
  font-weight: bold;_x000D_
  padding: 2px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table id="DataTable"></table>
_x000D_
_x000D_
_x000D_


For very advanced JSON objects to HTML tables you can try My jQuery Solution that is based on this closed thread.

var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];

// Builds the HTML Table out of myList json data from Ivy restful service.
 function buildHtmlTable() {
      addTable(myList, $("#excelDataTable"));
 }

function addTable(list, appendObj) {
    var columns = addAllColumnHeaders(list, appendObj);

    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = list[i][columns[colIndex]];

            if (cellValue == null) {
                cellValue = "";
            }

            if (cellValue.constructor === Array)
            {
                $a = $('<td/>');
                row$.append($a);
                addTable(cellValue, $a);

            } else if (cellValue.constructor === Object)
            {

                var array = $.map(cellValue, function (value, index) {
                    return [value];
                });

                $a = $('<td/>');
                row$.append($a);
                addObject(array, $a);

            } else {
                row$.append($('<td/>').html(cellValue));
            }
        }
        appendObj.append(row$);
    }
}


function addObject(list, appendObj) {
    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');

        var cellValue = list[i];

        if (cellValue == null) {
            cellValue = "";
        }

        if (cellValue.constructor === Array)
        {
            $a = $('<td/>');
            row$.append($a);
            addTable(cellValue, $a);

        } else if (cellValue.constructor === Object)
        {

            var array = $.map(cellValue, function (value, index) {
                return [value];
            });

            $a = $('<td/>');
            row$.append($a);
            addObject(array, $a);

        } else {
            row$.append($('<td/>').html(cellValue));
        }
        appendObj.append(row$);
    }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
    var columnSet = [];
    var headerTr$ = $('<tr/>');

    for (var i = 0; i < list.length; i++) {
        var rowHash = list[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    appendObj.append(headerTr$);

    return columnSet;
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?