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
- How to fetch specific columns in a row and transfer it to another table
- Link wrapped around an image click event in Jquery
- Why does the alert coming from my loop always return the last value, not each iteration value?
- How to hide/show more text within a certain length (like youtube)
- stopping mousewheel event from happening twice in OSX
- Notification.requestPermission throws an error in Mac versions of Safari
- Browser detection Plugin?
- jQuery datatable checkall
- How to toggle between glyphicon classes
- jQuery is(':visible') acting funny.
- Can I start with jQuery (or Node.js) with "NIL" knowledge of JavaScript?
- Change background image dynamically on checked checkbox
- How use JQuery each function in typescript
- jquery, ajax and CKEditor - how to "unbind" a CKEditor instance
- Importing contacts from gmail, yahoo, hotmail facebook and twitter
- Jquery- Get the value of first td in table
- jQuery click() not working in Google Chrome extension
- Prototype .Mousemove equivalent
- Replace keyCode in IE 11
- How to upload file in fat free frame work?
- clean example of directions with google maps in jquery mobile?
- Efficient AutoSuggest with jQuery?
- JQUERY Slider get value
- How to send multiple variables in jeditable?
- Make @Html.Checkboxfor fire JQuery click event
- How to draw a circle to denote selection in html
- jQuery parseJSON Multidimensional-array
- How to conditionally load a jQuery plugin?
- jQuery draggable + droppable - Physically move dragged item into dropped container
- jquery referencing multiple elements in one line
- Can I move an option at the end of the select list?
- HTML5 and the mystery charset
- JQuery autocomplete dropdown menu position
- Google map - tricking computer to take single click as double click
- jQuery toggleClass doesn't work with label
- How to call a function when all elements (called by ajax) have been loaded?
- Append HTML-escaped text: jQuery
- Why do I get "Uncaught TypeError: Cannot read property" error with this variable?
- Concatenate string through for loop
- Passing data between jQuery and Servlet
- How to kill a javascript setTimeout loop
- How to update jEditable text field when user click mouse outside the form?
- How can I redirect a page to itself in JavaScript?
- Modify a subset of html and append it with jquery
- jQuery 'If' statement string comparison not working
- Which Javascript history back implementation is the best?
- PHP Javascript Uncaught SyntaxError: Unexpected token ILLEGAL
- js/html5 Displaying local storage
- Getting jStorage to work
- How to pass a string value as a reference in javascript and change it over there
- How to disable mouse scroll wheel scaling with Google Maps API
- How to make a button that will uncheck all checkboxes?
- background image event handler
- jQuery.Deferred() / Promises functionality in GWT?
- Leaflet: Use dynamic filters in GeoJSON layer
- jQuery.data() and cross browser compatibility?
- jQuery: Making simultaneous ajax requests, is it possible?
- How to change id value iterating by class
- How to get tinymce content in jquery?
- Decimal is not validated correctly in MVC 3 with jQuery Validator
- Floating Images mess up Bootstrap Scrollspy
- Add panels to Bootstrap 3 accordion dynamically
- cloning elements, avoiding more than one clone at a time when adding
- Closure event delegation - event listener on DOM parent that covers children/descendants of a given class
- Are the :text, :radio, :checkbox, etc selectors still deprecated in 1.9.0?
- How to handle fail of $.when promise?
- jquery ajax / django - present form in a bootstrap modal and re-show if validation was not successful
- JQuery Ui or AjaxControlToolkit?
- Include buttons inside typeahead suggestions using Backbone
- How to find how many pixels down a div is relative to a parent div (jquery)
- Modal form Submission to PHP using Jquery .ajax
- How to allow play only one embedded YouTube video on page?
- Good practice method for loading JavaScript via ajax
- Make the selected option in a Select box always appear at the top
- jQuery UI Slider conflicts with Mootools.fx slide
- On click, hide div and remove required attribute
- Replace dots with double digit numbers slick slider
- How to store values from multiple select fields to an array and update array on option change?
- jQuery Ajax access custom response headers
- How to execute javascript in external HTML/SVG file in pure JavaScript?
- using jQuery .each() method on single-element id-selector
- Centering element inside an element (jQuery)
- What are the best practices when using jQuery Ajax calls?
- Grid view at center of page in jquery mobile
- Google Dart Forms working example
- using jquery $.ajax to call a PHP function
- jQuery multiple selector with $(this)
- jQuery hide parent div if child div is empty
- Detect when "cursor position inside input change" in jQuery?
- close div when clicked outside the div area
- JS array apparently doesn't have a length
- Open link in new window with Jquery
- How do I update the html displayed for each iteration of a for loop in javascript / jquery?
- What is a good jQuery/Ajax lightbox plugin?
- Need good jquery multiselect plugin with predictive search feature
- MVC - Loading screen / disable button before and after downloading a file
- Using regex with jQuery in binding events
- jQuery: what is it "forbidden" to do in plain Javascript
- jQuery, JSON and Apache problem
- document execCommand copy not working with AJAX
- HTML5 dragleave fired when hovering a child element
- iCheck library: value of selected radio button
- Why do my jQuery checkbox.change events only fire on leavefocus in IE but they happen onclick in FF?
- Target certain div / li with css attribute with JQuery
- Restructuring HTML using jQuery
- jQuery DataTables: Uncaught TypeError: Cannot read property 'length' of undefined
- Remove a class and hide a div on click of button using jquery
- event.preventDefault() Causing :hover pseudo class to stick
- jQuery sorting of div elements based on count, and date/time (timestamp)
- How do I maintain GET Url arguments across multiple pages with jQuery and PHP?
- how to disable the jquery dialog buttons
- Woocommerce: Detect where Add to Cart button was clicked and run different code
- How to calculate two input form fields and put the value in another without submitting the form using jquery?
- How to make an element with opacity 0 unclickable
- What would $('div, span', $('.test')).selector output? jQuery bug?
- Detect google ads click
- How to hookup jQuery autocomplete with POST query to remote data source?
- Fullcalendar.io: how to display one event per line in agendaWeek then mix all in one?
- Modifying a query string without reloading the page
- Add rows dynamically hainf html helper in asp.net mvc
- JQuery .on() change event not firing(page is inside a .load())
- jQuery Plugin: Using callback to alter plugin behavior
- Disable Sound In Browser Window With JS or Jquery
- How to change div order in javascript
- How to wrap word into span on user click in javascript
- JS ProgressEvent is only fired when finished
- How filter and sort array by category and date using Lodash
- BOOTSTRAP trigger tooltip on input element only if input val length < n
- Counter for TinyMCE is not working as expected
- remove first element from array and return the array minus the first element
- stopping content from 'jumping' when navbar fixes to top of screen
- jQuery validation field by range
- ESLint dollar($) is not defined. (no-undef)
- Multiple .on('click'... function binded only to 1st <div>
- Jquery and Ajax to Dynamically load IFrame
- How to grab return value from an ajax call?
- Submit form without page refresh using Jquery not working
- jQuery Array is not finding objects in my array?
- How Do I Prevent Enter Key Submit in jQuery?
- Reactjs URL.createObjectURL is not a function
- How does validity.valid works?
- How Do You Use jQuery to Simplify Your MVC Views?
- jQuery UI custom AutoComplete - `_renderItem` and `_renderMenu` not working
- How to change Django date format to dd/ mm/ yy?
- Minimize / Maximize div's with jQuery
- Refresh page if websocket not received for some time
- keydown combination
- jquery dataTables plugin: dynamically modify ajaxSource
- jQuery test if element1 is descendant of element2
- Bootstrap Typeahead with AJAX source: not returning array as expected