How to Convert JSON Data to HTML Table using jQuery DataTables Plug-in

On 12/11/2017

Hi, this time I have come up with a jquery basics tutorial which discusses about how to convert json to html table. In simple terms we are going to use jquery to display data from a json file in neat table format with added pagination and search options to it. To make our life easier there is an excellent jquery plug-in called ‘DataTables’ which we will use for this task. DataTables is a flexible jquery tool which adds up advanced interaction controls to any HTML table. Using this we can easily add pagination, instant search or multi-column ordering to the html table. Moreover it supports all modern day data sources like DOM, JavaScript, Ajax and server-side processing.

Convert JSON Data to HTML Table using jQuery

As an example let’s take the below sample json file which contains an array of objects and display it in html table using datatables.

Don't Miss: How to Create Responsive Carousel Image Slider

Also Read: How to Create Image Lightbox Effect with jQuery

empdata.json

{
  "data": [
    {
      "name": "Garrett Winters",
      "designation": "Accountant",
      "salary": "$170,750",
      "joining_date": "2011/07/25",
      "office": "Tokyo",
      "extension": "8422"
    },
    {
      "name": "Brielle Williamson",
      "designation": "Integration Specialist",
      "salary": "$372,000",
      "joining_date": "2012/12/02",
      "office": "New York",
      "extension": "4804"
    },
    {
      "name": "Ashton Cox",
      "designation": "Junior Technical Author",
      "salary": "$86,000",
      "joining_date": "2009/01/12",
      "office": "San Francisco",
      "extension": "1562"
    },
    {
      "name": "Airi Satou",
      "designation": "Accountant",
      "salary": "$162,700",
      "joining_date": "2008/11/28",
      "office": "Tokyo",
      "extension": "5407"
    },
    {
      "name": "Caesar Vance",
      "designation": "Pre-Sales Support",
      "salary": "$106,450",
      "joining_date": "2011/12/12",
      "office": "New York",
      "extension": "8330"
    },
    {
      "name": "Shad Decker",
      "designation": "Regional Director",
      "salary": "$183,000",
      "joining_date": "2008/11/13",
      "office": "Edinburgh",
      "extension": "6373"
    },
    {
      "name": "Cedric Kelly",
      "designation": "Senior Javascript Developer",
      "salary": "$433,060",
      "joining_date": "2012/03/29",
      "office": "Edinburgh",
      "extension": "6224"
    },
    {
      "name": "Haley Kennedy",
      "designation": "Senior Marketing Designer",
      "salary": "$313,500",
      "joining_date": "2012/12/18",
      "office": "London",
      "extension": "3597"
    },
    {
      "name": "Colleen Hurst",
      "designation": "Javascript Developer",
      "salary": "$205,500",
      "joining_date": "2009/09/15",
      "office": "San Francisco",
      "extension": "2360"
    },
    {
      "name": "Dai Rios",
      "designation": "Personnel Lead",
      "salary": "$217,500",
      "joining_date": "2012/09/26",
      "office": "Edinburgh",
      "extension": "2290"
    },
    {
      "name": "Herrod Chandler",
      "designation": "Sales Assistant",
      "salary": "$137,500",
      "joining_date": "2012/08/06",
      "office": "San Francisco",
      "extension": "9608"
    },
    {
      "name": "Rhona Davidson",
      "designation": "Integration Specialist",
      "salary": "$327,900",
      "joining_date": "2010/10/14",
      "office": "Tokyo",
      "extension": "6200"
    },
    {
      "name": "Sonya Frost",
      "designation": "Software Engineer",
      "salary": "$103,600",
      "joining_date": "2008/12/13",
      "office": "Edinburgh",
      "extension": "1667"
    },
    {
      "name": "Jena Gaines",
      "designation": "Office Manager",
      "salary": "$90,560",
      "joining_date": "2008/12/19",
      "office": "London",
      "extension": "3814"
    },
    {
      "name": "Quinn Flynn",
      "designation": "Support Lead",
      "salary": "$342,000",
      "joining_date": "2013/03/03",
      "office": "Edinburgh",
      "extension": "9497"
    }
  ]
}

Now let's see about converting this json data to html table.

Step 1: First you need the datatables plug-in in place to start working. So download datatables plug-in here and extract its contents and move ‘media’ directory to your working folder.

Step 2: Having the required datatables files in place, now we have to link them to the html file. Create a file ‘index.html’ and link the datatables ‘css’ and ‘js’ files like this.

<html>
<head>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>

    ...

    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
</body>
</html>

Remember to include the jquery library before datatables ‘js’ file as the plug in is built over jquery.

Step 3: Now it's time to create a html table structure which we will map to our json data source later. We should determine what are the columns we want to appear on the table and create the table's header and footer with appropriate column names.

<table id="empTable" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th>Name</th>
            <th>Designation</th>
            <th>Office</th>
            <th>Extension</th>
            <th>Joining Date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Using the css class ‘.display’ will create the table with alternative striped rows (zebra cross style).

Step 4: Finally we should populate the html table with the data from json source by mapping to the right table columns.

<script type="text/javascript">
$( document ).ready(function() {
    $('#empTable').dataTable({
        "ajax": "empdata.json",
        "columns": [
            {"data": "name"},
            {"data": "designation"},
            {"data": "office"},
            {"data": "extension"},
            {"data": "joining_date"},
            {"data": "salary"}
        ]
    });   
});
</script>

- The dataTable() method will initialize the datatables. Its behavior can be controlled by passing parameters for various options and we have used two options in the above code. (I planned to keep the code as simple as possible and used only the basic options required but you can try out more).

- The ajax option will load the data from the given ajax source. Here in our case it’s the path to the json file.

- The columns option will map the table columns to the data source keys.

Now run the index.html file and you can see a nicely designed html table with added enhancements like instant-search at the top and pagination links at the bottom. You can also sort the table columns like you prefer.

display-json-data-in-html-table-datatables-jquery-example
JSON Data Displayed in HTML Table using jQuery Datatables Plug-in

Complete Code for index.html

<!DOCTYPE html>
<html>
<head>
    <title>Display JSON File Data in Datatables | Example</title>
    <!-- link datatables css -->
    <link rel="stylesheet" type="text/css" href="/path/to/jquery.dataTables.css">
</head>
<body>
    <table id="empTable" class="display" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Designation</th>
                <th>Office</th>
                <th>Extension</th>
                <th>Joining Date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
    
    <!-- load jquery -->
    <script type="text/javascript" src="/path/to/jquery-1.10.2.js"></script>
    <!-- load datatables js library -->
    <script type="text/javascript" src="/path/to/jquery.dataTables.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
        $('#empTable').dataTable({
            "ajax": "empdata.json",
            "columns": [
                {"data": "name"},
                {"data": "designation"},
                {"data": "office"},
                {"data": "extension"},
                {"data": "joining_date"},
                {"data": "salary"}
            ]
        });   
    });
    </script>
</body>
</html>

I hope this basic jquery tutorial gives you a good idea about converting json data to html table using datatables jquery plugin.

Read Also:

As said earlier it's a highly flexible tool and provides wide range of options to completely customize the looks and behavior of the html tables to meet your requirements. Don't hesitate to try out :-)

17 comments:

  1. I did a cut-n-paste.
    all files are where they should be.

    empdata.json?_=1450987177810 Failed to load resource: the server responded with a status of 404 (Not Found)? what is it looking for?

    ReplyDelete
    Replies
    1. It seems like the json file is missing. It has been provided at the top of the article. Just make sure you create 'empdata.json' file in your working folder.

      Hope this solves the issue!
      Cheers.

      Delete
    2. This problem occurs in chrome even if empdata.json file exists. It works fine in safari.

      Delete
    3. Any idea how to resolve the issue of the JSON data missing in Chrome?

      Delete
    4. Hi! This one sends HTTP request and if you simply open it as file in chrome, it throws ajax error. So run it in localhost as you do with server script files.

      localhost/path/to/file/index.html

      This works for chrome.

      However I notice other browsers like Firefox or safari simply run it as a HTML file and loads the table. No issues with them. Chrome is picky :)

      Delete
  2. Thanks!Good article!Clarified somethings and was able to get it working!

    ReplyDelete
  3. Hi I have followed the steps closely and all works fine however when I use my own data json file it's not displaying. The error is can't read json file but it's all validated correctly. Any ideas??

    ReplyDelete
    Replies
    1. The problem seems to be with your own json file. Even a single mismatch quote would raise such issues with json. Make sure json is valid and there is not mismatch in table column names.

      If the problem persists share your json data with us so that I can help!

      Cheers.

      Delete
  4. It seems that for some reason I can't change the object name of data to something else what am I doing wrong?? cheers

    ReplyDelete
  5. SHould it be a json file or can the input be a json object as well ?

    ReplyDelete
  6. What about url json data? Instead of that static empdata.json?

    ReplyDelete
  7. Valli, thank you for this excellent resource! I managed to get your example working but I cannot seem to replicate this with my data. I get a "Loading..." message in my table. When I click on the number of records selector in the top left of the webpage and change the number of items to be displayed, the message in the table changes to "No data available in table". Any ideas as to what may be going on?

    When I look at the Browser Console in Firefox, there are 3 alerts:
    1) Use of Mutation Events is deprecated. Use MutationObserver instead
    2) not well-formed (this refers to the json file but my format is exactly the same as empdata.json)
    3) TypeError: aData is undefined

    Any help would be gratefully accepted.

    Thanks,
    Venky

    ReplyDelete
  8. Hi Valli, I wanted to let you know that I managed to get my table to display correctly. Thank you for your help! - Venky

    ReplyDelete
  9. We followed all the steps but we are not able to load the json data in the html

    ReplyDelete
  10. We followed the steps but we are not able to load the json file in html table, can u pls help.

    ReplyDelete

Contact Form

Name

Email *

Message *