Creating HTML tables from JSON data in JavaScript

 •  Filed under json, data, html tables, javascript

A few weeks ago I have written a simple JavaScript library to convert JSON data to an HTML table, and vice versa if you need it. With that library comes even more functionality, like the ability to filter (search) through table rows and the ability to filter JSON data for a multi-page table layout.

You can find my project on GitHub.

This is the table and search box HTML code that I used for this article:

<div class="container">  
  <div class="row">
    <br>
    <input type="text" name="searchbox" id="searchbox" style="width: 100%;"><br><br>
  </div>

  <div class="row">
    <table id="userTable" class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>Bart</td>
       </tr>
        <tr>
          <td>2</td>
          <td>Nick</td>
        </tr>
        <tr>
          <td>3</td>
          <td>Jason</td>
        </tr>
        <tr>
          <td>4</td>
          <td>Fred</td>
        </tr>
        <tr>
          <td>5</td>
          <td>Ed</td>
        </tr>
        <tr>
          <td>6</td>
          <td>Peter</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>  



So let's dive deeper into some code examples that you can use to create your tables from JSON data:


Example 1: Convert an HTML table to JSON

$(document).ready(function()
{
  // Create a new JSONTable Object from the basicTable table.
  var jsonTable = new JSONTable($("#basicTable"))

  // Convert existing HTML table to a JSON object.
  var tableData = jsonTable.toJSON()
})



Example 2: Search through a table with the filter function

$(document).ready(function()
{
  // Create a new JSONTable Object from the basicTable table.
  var jsonTable = new JSONTable($("#basicTable"))

  // Convert existing HTML table to a JSON object.
  var tableData = jsonTable.toJSON()

  // Create a jQuery event handler on the searchbox.
  $("#searchbox").on('input', function(e) {
    jsonTable.filter($(this).val())
  })
})



Example 3: Create a new HTML table directly from JSON data

// Build a JSON object array with items which are to be included in the table.
var jsonData = [{"ID":"1","Name":"User1"},{"ID":"2","Name":"User2"},{"ID":"3","Name":"User3"},{"ID":"4","Name":"Admin1"},{"ID":"5","Name":"Admin2"}]

// Create a new table inside the body tag
$("body").append("<table id='testTable'></table>")

// Spawn a new JSONTable object on the newly created table
var jsonTable = new JSONTable($("#testTable"))

// Create HTML table (data)structure from JSON data
jsonTable.fromJSON(jsonTest)  



You should definitely try these examples. Good luck!