In this tutorial, I will explain how you can display JSON data in an HTML table using jquery dynamically.
When I get this task from my project manager then I’m looking for any jQuery or javascript plugin that creates a dynamic table using JSON data.
Because I don’t want to define the header and the columns, the plugin should read the keys in the JSON data and generate columns and header of the table.
Basically, my task is to convert JSON data to an HTML table.
But later I decided to write my own code instead of using the third-party plugin. so here I’m going to share my code with other developers also.
The purpose of this article is to explain how you can Dynamically generate a table from a JSON array in javascript.
In this article, We will cover the below points in the
- Populate html table with json data
- How to create dynamic table with JSON data?
- Display json data in html table using jquery dynamically
- Converting json data to a html table
I have JSON array data which has contains the employee with ‘EmployeeID’, ‘EmployeeName’, ‘Address’, ‘City’, ‘Country’ fields.
var employess = [ { "EmployeeID": "1", "EmployeeName": "Hanari Carnes", "Address": "Rua do Paço, 67", "City": "Rio de Janeiro", "Country": "Brazil" }, { "EmployeeID": "2", "EmployeeName": "Wolski", "Address": "ul. Filtrowa 68", "City": "Walla", "Country": "Poland" }, { "EmployeeID": "3", "EmployeeName": "Lehmanns Marktstand", "Address": "Magazinweg 7", "City": "Frankfurt a.M.", "Country": "Germany" } , { "EmployeeID": "4", "EmployeeName": "Let's Stop N Shop", "Address": "87 Polk St. Suite 5", "City": "San Francisco", "Country": "USA" }, { "EmployeeID": "5", "EmployeeName": "Lazy K Kountry Store", "Address": "12 Orchestra Terrace", "City": "Walla Walla", "Country": "USA" } , { "EmployeeID": "6", "EmployeeName": "Island Trading", "Address": "Garden House Crowther Way", "City": "Cowes", "Country": "UK" } ]
Now I want to generate a table from this employee JSON using Javascript.
Convert json array data to a html table
<!DOCTYPE html>
<html>
<head>
<title> Use of JQuery to Add Edit Delete Table Row </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
<div class="container">
<h1>Employee List</h1>
<br />
<div id="employeedivcontainer">
</div>
</div>
</body>
</html>
<script type="text/javascript">
var employess = [
{
"EmployeeID": "1",
"EmployeeName": "Hanari Carnes",
"Address": "Rua do Paço, 67",
"City": "Rio de Janeiro",
"Country": "Brazil"
},
{
"EmployeeID": "2",
"EmployeeName": "Wolski",
"Address": "ul. Filtrowa 68",
"City": "Walla",
"Country": "Poland"
},
{
"EmployeeID": "3",
"EmployeeName": "Lehmanns Marktstand",
"Address": "Magazinweg 7",
"City": "Frankfurt a.M.",
"Country": "Germany"
}
,
{
"EmployeeID": "4",
"EmployeeName": "Let's Stop N Shop",
"Address": "87 Polk St. Suite 5",
"City": "San Francisco",
"Country": "USA"
},
{
"EmployeeID": "5",
"EmployeeName": "Lazy K Kountry Store",
"Address": "12 Orchestra Terrace",
"City": "Walla Walla",
"Country": "USA"
}
,
{
"EmployeeID": "6",
"EmployeeName": "Island Trading",
"Address": "Garden House Crowther Way",
"City": "Cowes",
"Country": "UK"
}
]
convertJsontoHtmlTable();
function convertJsontoHtmlTable()
{
//Getting value for table header
// {'EmployeeID', 'EmployeeName', 'Address' , 'City','Country'}
var tablecolumns = [];
for (var i = 0; i < employess.length; i++) {
for (var key in employess[i]) {
if (tablecolumns.indexOf(key) === -1) {
tablecolumns.push(key);
}
}
}
//Creating html table and adding class to it
var tableemployee = document.createElement("table");
tableemployee.classList.add("table");
tableemployee.classList.add("table-striped");
tableemployee.classList.add("table-bordered");
tableemployee.classList.add("table-hover")
//Creating header of the HTML table using
//tr
var tr = tableemployee.insertRow(-1);
for (var i = 0; i < tablecolumns.length; i++) {
//header
var th = document.createElement("th");
th.innerHTML = tablecolumns[i];
tr.appendChild(th);
}
// Add employee JSON data in table as tr or rows
for (var i = 0; i < employess.length; i++) {
tr = tableemployee.insertRow(-1);
for (var j = 0; j < tablecolumns.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = employess[i][tablecolumns[j]];
}
}
//Final step , append html table to the container div
var employeedivcontainer = document.getElementById("employeedivcontainer");
employeedivcontainer.innerHTML = "";
employeedivcontainer.appendChild(tableemployee);
}
</script>
Code explanation
I’m looping through the employee array in order to extract the headers of the table.
//Getting value for table header // {'EmployeeID', 'EmployeeName', 'Address' , 'City','Country'} var tablecolumns = []; for (var i = 0; i < employess.length; i++) { for (var key in employess[i]) { if (tablecolumns.indexOf(key) === -1) { tablecolumns.push(key); } } }
Here we are creating an HTML table element and adding class to it.
//Creating html table and adding class to it var tableemployee = document.createElement("table"); tableemployee.classList.add("table"); tableemployee.classList.add("table-striped"); tableemployee.classList.add("table-bordered"); tableemployee.classList.add("table-hover")
we generate the header of the HTML table using
//Creating header of the HTML table using //tr var tr = tableemployee.insertRow(-1); for (var i = 0; i < tablecolumns.length; i++) { //header var th = document.createElement("th"); th.innerHTML = tablecolumns[i]; tr.appendChild(th); }
Adding employee JSON data in the table
//Creating header of the HTML table using //tr var tr = tableemployee.insertRow(-1); for (var i = 0; i < tablecolumns.length; i++) { //header var th = document.createElement("th"); th.innerHTML = tablecolumns[i]; tr.appendChild(th); }
Append HTML table to the container div
//Final step , append html table to the container div var employeedivcontainer = document.getElementById("employeedivcontainer"); employeedivcontainer.innerHTML = ""; employeedivcontainer.appendChild(tableemployee);
JSON Basic concept
JSON is a ‘lightweight data format’ which can be easily understood, it is very easy for any machine to parse and generate it. Before JSON, XML (Extensible Markup Language) was used as the primary data format inside web services. But after the advent of JSON, the use of XML has reduced a lot. Because it is a very lightweight format in comparison to XML.
A JSON file can be recognized with a ” .json ” extension. The JSON data is kept inside a .json file. The JSON file consists of plain text which is easy to read and understand. The .json file can be opened and examined and can be sent over the Internet without any problems.
The full form of JSON is “JavaScript Object Notation”, while the full form of XML is “Extensible Markup Language”.
JSON is a simple text-based format, whereas it is a Markup Language.
JSON is very popular because it is a lightweight format, whereas XML contains tags, properties, etc. Because of this, it is heavier.
It does not support namespace and comment, supports comment and namespace in XML.
Data in JSON is in the pair of keys and values and is like a simple object. Whereas the data in XML is in the format of tags which is a bit difficult as compared to JSON so nowadays JSON is being used inside most of the software applications.
Feature
- JSON is a Human Readable Format that can be easily understood and read by anyone.
- JSON is also called language independent because it does not work for any language.
- It supports all popular programming languages like JAVA, PYTHON, C, C++, C#, PHP, etc.
- It is very easy to access and organize.
- Its most important advantages are that it is a very light format.
- Due to JSON, server-side parsing is very fast so that the response can be delivered to the user in the shortest possible time.
- It supports all browsers and operating systems.
- Any type of media files such as Video, Audio, Images, and any type of binary information cannot be transferred through JSON.
- There is no error handling inside JSON.
- One of the most dangerous disadvantages of JSON is that when you use any untrusted services and browsers, the service that gives a wrapped JSON response increases the chances of your application being hacked.
The post Display JSON data in HTML table using JavaScript dynamically appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Convert text node into HTML element using JQuery
- Can't catch an <a> with .click in jQuery
- IE6: Background-Image Load Event
- Make callback after play button is pushed - Youtube embed video
- Input appears disabled in IE, but is not disabled
- ATM style decimal places
- Populating child attribute using jQuery
- Add Auto Play To Existing Image Slider
- AJAX load and page scrolling
- javascript/jquery generate input element
- "VIDEOJS: WARN: Player "media" is already initialized" when it is not
- jQuery date picker multi select and unselect
- Behaviour of last elements in grid
- Rails .js.erb templates no longer work with Webpack
- Jquery only works once per page load - want it work more than once without having to reload page
- Open a Bootstrap Modal automatically from an external link
- Document.domain and <iframe>s breaks the "Back" button in Internet Explorer
- Send user's geolocation to server every minute
- How do I convert a CSS background-position property from percentages into pixels?
- Uncaught TypeError: Cannot read property 'nodeName' of undefined
- how to use jQuery to show up a non-modal dialog?
- Stub out a jQuery selector call?
- jQuery escaping special characters
- jquery retrieve relatedTarget.data('url') value
- How can I fade out, change test and then fade in with jQuery cleanly?
- how to make desired json tree from simple json
- Differences between document.ready and $function
- When emptying a tag, do the event-attached-buttons inside get garbage collected?
- jQuery - how to test if selector matches anything?
- How to get Dom object's content include itself?
- scrollTop() returns 0 in chrome
- How to get JQuery.trigger('click'); to initiate a mouse click
- Can jQuery be used to select elements from a returned string html?
- QUnit strange behavior with fixture, tests alternately failing and passing
- Where to set Ace editor blockScrolling?
- How to display an image file name in input field after uploading an image in jQuery
- Difference between handling $("form").submit or an <input type="submit"> click event?
- How to trigger change event for Chosen (jQuery)
- Post comments on Facebook page via console
- Are jQuery's hide and slideUp methods equivalent?
- Silverlight and "z-index"
- Selenium.click not working on some anchor elements
- jQuery Mobile, open dialog
- Why can't I make jQuery calls like $.whatever()?
- Video canplay event triggers thousands of times per second
- How do I add a preview text to my custom built autocomplete?
- jQuery .text() shows double text
- Is it correct to pass model reference directly to HTML element?
- Set radio button 'checked' in jquery based on ID
- How to resize image to fit DIV jQuery
- JavaScript - Recursively Finding Parent Nodes
- jQuery - Redirect with post data
- why does jquery's .load() ignore <script>?
- Fastest possible way in jQuery to filter "Radios + Select + Checkbox" together simultaneously
- Select2 does not show placeholder if initially hidden
- Jquery+wcf. Problem with basic authentication
- Overriding jQuery default ajaxError for a specific status code
- Adding a data attribute(with special characters) to a dom element using jquery
- Jcrop not working on bootstrap 3 modal
- owl carousel - Set different items number for each of many sliders placed on the same page
- Assign an ID to a DIV using javascript
- jQuery Validate Plugin - Validate Hidden Field by Name
- jQuery animate height to auto
- Disable all form controls on a web page
- Sortable('toArray') or sortable('serialize')
- jquery with update panel
- Traversing along Upper & Lower Siblings efficiently
- jQuery: Do I need both keyUp and change events?
- How to delay execution in between the following in my javascript
- Passing JSON data from php to html-data attribute and then to Javascript
- How to make single image in different dimentions / size
- Bootstrap and rendering Arshaw Fullcalendar in a tab
- jQuery Sortable not working in Android mobile
- jQuery: How to remove query string from a link?
- jQuery Ajax not working in iOS (with list.js)
- Full height image on mobile device
- Menu burger animation toggle full page menu
- CSS3 text-shadow effect with jQuery
- Drag and Drop file download from Website/Browser to local filesystem
- Javascript TRUE is not defined or in quotes
- How can I check string starts with using javascript / jQuery?
- ASP.NET MVC Interview Questions
- Slick.js appendarrows doesn't work for multiple carousels
- AngularJS CORS don't send all cookies with credential, but jQuery send
- Check if margin-left is a certain percentage
- JQuery and JSON array - How to check if array is empty or undefined?
- HTML5 video & Chrome/Webkit
- Using Cocoon (Nested Forms) and jQuery sortable together
- jQuery - How to remove class if clicking outside of div or open/close button
- Angular JS API authentication
- jQuery modal dialog with postbacks in ASP.NET
- Keep checkboxes in html table algined
- Truncate paragraph first 100 character and hide rest content of paragraph to show/hide rest contenct with more/less link
- How to check if an object with an id property exists inside an array?
- Change text "searching" in jquery select2
- ASP.NET MVC Jquery validation won't fire if partial is loaded via ajax
- Jquery datepicker not working in Firefox
- How to hide api key using php?
- Disable and Enable ALL Hyperlinks using JQuery
- Creditcard expiry validation with two separate dropdowns for months and years
- Getting average of every item of multiple arrays into one array
- Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent
- jquery .each waiting for function to finish before continuing through loop
- Can JQuery.Validate plugin prevent submission of an Ajax form
- Encode HTML before POST
- IE Javascript error "Object doesn't support this property or method" within jQuery
- Regular expression to restrict 'n' digits before and after decimal point
- IgniteUI IgTileManager does not maintain the correct maximized tile location when switching layouts
- Is jQuery.ready() valid when used on iframe.contentDocument?
- Result of Trying to Insert an Element Before Itself
- How to set $jQval.unobtrusive.options ErrorPlacement function correclty
- Trigger right-click
- selectize.js - how can I disable the flashing cursor after the selected item?
- jQuery Validate 1.7 breaks $.getJSON() on jQuery 1.5?
- Slow jQuery animation in IE
- How to ignore click event when clicked on children
- Bootstrap: How to fade and then hide something using the default 'fade', 'hide', 'in' classes?
- jQuery-UI Draggable and Sortable
- jqplot, remove outside border
- jQuery Ajax GET JSON
- jquery draggable moves on 30 degrees only
- jQuery: Returning the value of a checkbox as an array?
- Jquery load https url
- sort array of ints based on another array of ints
- Get value from bootbox confirm callback function
- How to get the class of the clicked element?
- Adding jquery and custom scripts to a Wordpress theme
- IE9 jQuery Ajax Not Working
- jQuery does not update nested form in Rails
- Howto get cross-browser literal style string with JavaScript?
- How do I select an element with its name attribute in jQuery?
- Track only mouse move of hovered child element in a nested div tag
- Change checkbox icon class onclick in jQuery
- Set default value of select2 input
- IE8 and jQuery null pointers
- Binding Json data to a table in mvc 4
- Using jQuery with Typescript 2
- Is element in array js
- How to handle change of checkbox using jQuery?
- Grab values of an attribute from all elements in jQuery
- jQuery Hover event is not bound to the child element
- Iterate and Enumerate Key Value Pairs of Multiple Arrays in an Object
- Can a screen reader be "locked" within a DIV element?
- jQuery lightbox Gallery
- How to measure a time spent on a page?
- How to trigger a click on a link using jQuery
- Tooltip flickers while hovering on the tooltip
- How do I properly import jQuery plugins to Node.JS?
- Jquery Ajax loading image while getting the data
- Fire onchange event for TextBox when readonly is true