Explain Codes LogoExplain Codes Logo

Convert json data to a html table

javascript
dynamic-table-generation
json-data
vanilla-javascript
Nikita BarsukovbyNikita Barsukov·Feb 3, 2025
TLDR

Instant solution alert! Transform JSON data into an HTML table with JavaScript using these 4 cardinal steps:

  1. Parse the JSON into an array of objects.
  2. Construct a table and iterate over the array.
  3. For each object, inseminate a fresh row to the table.
  4. For each key-value pair in the object, inject a cell into the row.

Voila! Here’s a succinct code example:

const json = '[{"name":"John", "age":30}, {"name":"Jane", "age":27}]'; // These are not actual ages of John and Jane 🙊 const data = JSON.parse(json); //JSON becomes a JavaScript object const table = document.createElement('table'); // The birth of a HTML table // Create tableau from data data.forEach(item => { const row = table.insertRow(); // Create new row Object.values(item).forEach(text => { const cell = row.insertCell(); // For each pair, new cell is born cell.textContent = text; // The cell speaks! }); }); document.body.appendChild(table); // Add the table to the DOM family tree

This JavaScript snippet creates a table with rows for each object and cells for each property value.

jQuery for dynamic table generation

Accustomed to the jQuery way of life? For jQuery enthusiasts, creating tables is simplified as you dynamically iterate over your JSON data. Gone are the days of manually setting each column, let jQuery deal with the DOM interactions.

Desire column headers? Use the power of jQuery to conjure this magic:

const json = '[{"name":"John", "age":30}, {"name":"Jane", "age":27}]'; // Adding fictional people to our table const data = JSON.parse(json); //Translating JSON to JavaScript const table = $('<table></table>'); // Our HTML table canvas // Function to add headers from JSON keys function addAllColumnHeaders(data) { const columnSet = new Set(); // Unique collection for headers data.forEach(item => Object.keys(item).forEach(key => columnSet.add(key))); // Fill the collection const tr = $('<tr></tr>'); // A row for headers columnSet.forEach(header => tr.append($('<th></th>').text(header))); // Stamp headers table.append(tr); } // Bring the function to life addAllColumnHeaders(data); // Add the data from JSON to cells row by row data.forEach(item => { const tr = $('<tr></tr>'); // New row for each item Object.values(item).forEach(value => tr.append($('<td></td>').text(value))); // Data -> Cell -> Row table.append(tr); }); // Origami fold the table onto the body of your HTML $('body').append(table);

Get the jQuery rolling by simply including it from a CDN, and your JSON data will be transformed into an aesthetically pleasing table layout quicker than you can say abracadabra!

Level up with plugins

Does your project need a seamless table creation performance boost? Integrate existing jQuery plugins like JSON2HTML or jPut. These enhance the connection of your JSON data to HTML templates by applying placeholder syntax like {{keyName}}.

Visualize using jPut, and define your HTML template in your webpage:

<table> <tbody id="tbody" data-jput="jsonData"> <tr> <td>{{name}}</td> <td>{{age}}</td> </tr> </tbody> </table>

Cohere your JSON data to the template with this one-liner of jQuery:

$('#tbody').jPut({ jsonData: data // The secret handshake 🤝 });

Just like that, JSON data slides into the placeholders, resulting in a dynamically created table.

Vanilla JavaScript way

Prefer an approach without the touch of jQuery? Want to enhance security wall by restricting dependencies? Vanilla JavaScript can be a complete game changer too. Let’s show HTML injection who's boss:

const json = '[{"name":"John", "age":30}, {"name":"Jane", "age":27}]'; // Did anyone say JSON cookies? 🍪 const data = JSON.parse(json); // JSON cookie -> JavaScript object const table = document.createElement('table'); // Prototype of an HTML table // Function to generate column headers based on JSON keys addAllColumnHeaders(data); data.forEach(item => { const tr = document.createElement('tr'); Object.keys(item).forEach(key => { const td = document.createElement('td'); td.textContent = item[key]; // Injecting the data tr.appendChild(td); // The data has found its home }); table.appendChild(tr); // Completing the row }); document.body.appendChild(table); // And the table grows! // Dynamic generation of headers function addAllColumnHeaders(data) { const headerTr = document.createElement('tr'); if (data.length > 0) { Object.keys(data[0]).forEach(key => { const th = document.createElement('th'); th.textContent = key; // Extracted keys are now headers! headerTr.appendChild(th); }); table.appendChild(headerTr); } }

Essential points to ponder

While implementing these solutions, we should remember a few important aspects:

  • OnLoad Initialization: If your data is dynamic, run your table creation magic with onLoad to ensure your data is in sync.
  • Data Integrity: Double check existence of keys in your JSON data before leaping to add them to your table.
  • Document Structure: Don't forget the correct container (like a tbody with the id "tbody" for jPut) in your HTML to allow effective targeting.
  • Performance: Consider using cloneNode to duplicate nodes for efficiency when working with large data sets.
  • Customization: Embrace libraries and plugins, but don't shy away from tweaking them to fit your specific needs.