Recently I’m working on a project where I need to create an HTML form JSON data then first I thought Is there any jQuery or javascript plugin that I can use to create an HTML table based on JSON data?
I don’t want to define the table columns, the i just need the library that reads the keys in the JSON data and generates columns for the table. So I decided to write my own logic, we can do this task using multiple ways.
If you are a beginner in coding and currently you are trying to take the information from JSON file and create a table in HTML and then don’t worry, we will do this job in this post.
How to convert JSON with html table tag using JavaScript
I have rewritten the below code -using vanilla js and using DOM methods to prevent HTML injection for security.
Using vanilla js and using DOM methods
<!DOCTYPE html>
<html>
<head>
<title>Page Title</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>
</head>
<body>
<div class="container">
<div id="divcontent"></div>
</div>
<script type="text/javascript">
var jsondata = [
{
"id": 84,
"tourist_name": "Ammy",
"tourist_email": "ammy123@gmail.com",
"tourist_location": "USA",
"createdat": "2020-06-02T05:08:58.672851"
},
{
"id": 85,
"tourist_name": "shreya",
"tourist_email": "shreya.kumari4994@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T05:14:40.7655781"
},
{
"id": 86,
"tourist_name": "Jenny",
"tourist_email": "Jenny96@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T05:18:22.7652253"
},
{
"id": 87,
"tourist_name": "Apolo",
"tourist_email": "chandanjaishawal@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T12:56:51.9287121"
},
{
"id": 88,
"tourist_name": "Ajay Nagar",
"tourist_email": "aj222@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-04T08:48:53.8471058"
},
{
"id": 89,
"tourist_name": "AP",
"tourist_email": "ap.prak97@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-08T15:58:26.3844855"
},
{
"id": 90,
"tourist_name": "Alexa uodate",
"tourist_email": "alexathomas1975@gmail.com",
"tourist_location": "10281 Mission Gorge Rd, Santee, CA 92071, USA",
"createdat": "2020-06-09T14:04:12.9065286"
},
{
"id": 91,
"tourist_name": "Jennifer Mathis",
"tourist_email": "jennifermathis.89904@gmail.com",
"tourist_location": "USA",
"createdat": "2020-06-10T17:12:53.4353615"
},
{
"id": 92,
"tourist_name": "_Anand_",
"tourist_email": "ap.prak101@gmail.com",
"tourist_location": "Canada",
"createdat": "2020-06-11T05:55:13.7406625"
},
{
"id": 93,
"tourist_name": "Mark",
"tourist_email": "Mark.prak102@gmail.com",
"tourist_location": "France",
"createdat": "2020-06-11T06:07:06.939638"
}
]
var tableElement = document.createElement('table');
tableElement.classList.add("table");
tableElement.classList.add("table-striped");
var tbltr = document.createElement('tr');
var tblth = document.createElement('th');
var tbltd = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy restful service.
function CreateHtmlTableFromJson(JsonArray) {
var table = tableElement.cloneNode(false),
columns = CreateTableHeaders(JsonArray, table);
for (var i = 0, maxi = JsonArray.length; i < maxi; ++i) {
var tr = tbltr.cloneNode(false);
for (var j = 0, maxj = columns.length; j < maxj; ++j) {
var td = tbltd.cloneNode(false);
cellValue = JsonArray[i][columns[j]];
td.appendChild(document.createTextNode(JsonArray[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// In below code we are Adding header row to the html table and returns the columns.
function CreateTableHeaders(jsonarray, table) {
var columnSet = [],
tr = tbltr.cloneNode(false);
for (var i = 0, l = jsonarray.length; i < l; i++) {
for (var key in jsonarray[i]) {
if (jsonarray[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {
columnSet.push(key);
var th = tblth.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
var datacontainer = document.getElementById("divcontent");
datacontainer.innerHTML = "";
datacontainer.appendChild(CreateHtmlTableFromJson(jsondata));
</script>
</body>
</html>
Method 2:Convert json data to a html table using Jquery
Here I’m using jquery loop through all the json data to make a table using jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div id="divresult"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
var jsondata = [
{
"id": 84,
"tourist_name": "Ammy",
"tourist_email": "ammy123@gmail.com",
"tourist_location": "USA",
"createdat": "2020-06-02T05:08:58.672851"
},
{
"id": 85,
"tourist_name": "shreya",
"tourist_email": "shreya.kumari4994@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T05:14:40.7655781"
},
{
"id": 86,
"tourist_name": "Jenny",
"tourist_email": "Jenny96@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T05:18:22.7652253"
},
{
"id": 87,
"tourist_name": "Apolo",
"tourist_email": "chandanjaishawal@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-02T12:56:51.9287121"
},
{
"id": 88,
"tourist_name": "Ajay Nagar",
"tourist_email": "aj222@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-04T08:48:53.8471058"
},
{
"id": 89,
"tourist_name": "AP",
"tourist_email": "ap.prak97@gmail.com",
"tourist_location": "India",
"createdat": "2020-06-08T15:58:26.3844855"
},
{
"id": 90,
"tourist_name": "Alexa uodate",
"tourist_email": "alexathomas1975@gmail.com",
"tourist_location": "10281 Mission Gorge Rd, Santee, CA 92071, USA",
"createdat": "2020-06-09T14:04:12.9065286"
},
{
"id": 91,
"tourist_name": "Jennifer Mathis",
"tourist_email": "jennifermathis.89904@gmail.com",
"tourist_location": "USA",
"createdat": "2020-06-10T17:12:53.4353615"
},
{
"id": 92,
"tourist_name": "_Anand_",
"tourist_email": "ap.prak101@gmail.com",
"tourist_location": "Canada",
"createdat": "2020-06-11T05:55:13.7406625"
},
{
"id": 93,
"tourist_name": "Mark",
"tourist_email": "Mark.prak102@gmail.com",
"tourist_location": "France",
"createdat": "2020-06-11T06:07:06.939638"
}
]
$(document).ready(function () {
var html = '<table class="table table-striped">';
html += '<tr>';
debugger;
//creating table header
$.each(jsondata[0], function (index, item) {
html += '<th>' + index + '</th>';
});
html += '</tr>';
//creating table row and appending it in the table
$.each(jsondata, function (index, item) {
html += '<tr>';
$.each(item, function (secondindex, seconditem) {
html += '<td>' + seconditem + '</td>';
});
html += '<tr>';
});
html += '</table>';
//append html in html body
$('body').html(html);
});
</script>
</body>
</html>
*Thank you so much if you have a question please comment
JSON is a simple text based open standard data interchange format. It is completely independent language and most of it can be used with modern programming languages.
While Ajax applications commonly use JSON, Ajax is technically “Asynchronous JavaScript and XML.”
The full form of JSON is “JavaScript Object Notation” and it is pronounced “Jason.” It is most commonly used to transfer data between web applications and web servers.
While Ajax applications commonly use JSON, Ajax is technically “Asynchronous JavaScript and XML.”
JSON is a text-based data interchange format that is designed for the transmitting of structured data.
The full form of JSON is “JavaScript Object Notation” and it is pronounced “Jason.” It is most commonly used to transfer data between web applications and web servers.
JSON has many advantages over XML although XML serves only one purpose.
JSON files are saved with .json extension. Internet Media Type of JSON “application/json”.
The post Convert JSON data to HTML table using JavaScript 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 create a transparent region (div) over semi-transparent background?
- API Google Maps Javascript calling event listener inside context menu
- jQuery load tracking pixel and after that redirect
- Use json-time to display some things
- Change CSS class after scrolling 100% screen height down
- Update background after all items have loaded
- I want to have links that can search through my images
- JQuery mobile list prepend
- how can i do download of PDF archive of jasper report using AJAX?
- Javascript - Unintentional firing of event in parent div
- Dynamic Dropdown in HTML error
- Jquery hides container when it should be showing
- jscrollpage - where are the themes?
- JQuery-Get value from select option to use in PHP
- Jquery click event for button is not working inside ng-if div
- Sort div by span class
- regex positive negative decimal numbers, comma separated
- jquery change image menu when selected
- Can't show looped JSON data on a div
- jquery ie8 $(selector).html(large data) can not display
- Change table contents depending on link clicked
- Properly exposing C# methods to jQuery
- jquery datatable table tools export to excel is not showing me the table data in file
- jqueryUI(Mobile) to ajax content
- How to select all children (any level) and parents of a certain element with jQuery
- Bootstrap 2 Collapse Icon Does Not Change
- Diagonal corner to corner divs
- chartjs improvement display label
- getting values of the clicked row and assigning cell's values to corresponding inputs
- jQuery - Prevent a sortable element from going back into a sortable list after dragging has started
- jquery themeroller - out of the box example does not grey the modal dialog backgound
- Flexslider image <li> dynamically generated by php. Trying to create captions using alt text
- In JQM can i get a separate event for a listview and a checkbox inside listview?
- Select Option display issue
- get p tag text in jquery for ajax live search
- Get result back after form submit
- Webscrape data tables from a webpage, dynamically loaded
- How to execute the same JQuery code for different html elements?
- Using two Ajax calls to post then retrieve data
- Use show or shown in JavaScript
- Posting data to REST service in Cordova and Internal Server Error
- How to load image into <div> automatically without refreshing page after the image were upload to server using ajax/jquery in Java Struts 2?
- TableSorter jquery plugin how to resort auto-increment numbers
- Ajax request said successful submitted data but php does not respond
- Instragram hashtag search
- Custom Dropdown with left and right textbox
- Auto-resize custom horizontal scrollbar/slider?
- DOM access of meteor templates using js
- Counts from 1 to 1500 in 3 seconds jQuery isInViewport
- Convert jquery code to angular to add classes dynamically on function call from controller
- How to get the number of particular child elements for each matched element
- Async JavaScript Callback
- chart.js data wont update
- Click and If function after div change its content on user action
- dynamically inserted anchor tags are not working
- Jquery - Kerning Paragraph Text to Fit to Parent
- Wistia API play/pause button
- Uncaught SyntaxError: Unexpected string in jquery
- FullCalendar Event Resize count
- Expand a single row into multiple rows based on filters
- How to easily upload files without form submission (with jQuery + AJAX)
- why function is not called in xslt?
- CSS Position Help (horizontal sidebar showing up when animate content over)
- Toggle class to specific element depends on hash from URL
- How to save in local storage a background-color change in a table cell?
- Applying a style to a specific body class
- Storing element height in var via jquery
- flyout menu examples?
- Laravel 5.3: accessor value doesnot JSON encode
- jQuery - creating the first dynamic page before executing a function
- Smoothstate.js and Django - Form POST only triggered on second click
- Modal won't work in php echo
- Checkbox must stay checked on all pages
- Use jQuery ID Selector with CSS
- Update displayed div on form submit using JQuery
- Show div depending on select box selection
- Bootstrap tooltip usage with the actual example tooltip buttons?
- Use jquery variable and loop in Ajax post data
- Problem with AJAX GET function inside PHP FUNCTION
- Check if two different elements contain specific words and if so fire event with Jquery
- tango with django "Like Button" Not working
- get text of a list on click using jquery
- How to compare 2 values with client-side validation in ASP.NET MVC?
- How to embed a file in html using jquery.load() in chrome
- DotNetHighcharts- Can I assign my whole chart to a JS var after page load, for further manipulation
- How to move the canvas backward in javascript?
- Ajax call works in stand alone, but fails in wordpress
- Success function doesn't work
- Jquery tablesorter customize option for sorting
- Problem in replacing body contents with ajax from a django HttpResponse
- Safari does not animate when adding class to div
- Bootstrap modal change content on click
- Populate list only in current row
- How to make a fixed header change colour on scroll
- Adding Up dynamic data in a table not working jquery
- data not passed from view to controller in codeigniter
- Unable to handle scenario: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
- How to scrollIntoView target id element of href to center of page using jQuery
- Hash check for URL constantly firing function
- Jquery autosuggest
- SUM all values of an array of objects by array index of object property in JavaScript / JQuery
- Prevent click for Chocolat.js while dragging using slick.js
- TypeError: b.toLowerCase is not a function in bootstrap typeahead plugin
- RangeSliders disappears after .submit()
- Struts <s:submit> and Struts-jquery <sj:submit> will not work in same form Part 2
- Rails: loading partial with jQuery
- How to maintain outside dragging events from a cross-domain `iframe`?
- 404 while pushing JS variables to PHP, calling a PHP function, getting result as a JSON string to JS and possibly failing while working with it
- Cannot set class for row when check box clicked
- imageScroll js parallax Uncaught type error
- datepicker field authorizing specific characters
- Add a active link to custom ul in wordpress
- Encode form array elements into JSON using only JS or other client side libs
- jQuery setInterval if statement loop is not working
- TypeError Running jQuery Code Snippet
- Different random number for each item
- Replace special characters on a set with
- Float labels doesn't work when a value is pre-defined
- Vertically center layer within the user's viewable area on a long page
- Form validation with Ajax and PHP - return a variable from PHP to use in javascript function
- return jsonresult behaves unexpextedly with jquery post
- How to Process Ajax Result (Struts2)
- Get the closest className
- jquery fade doesnt work after clone?
- how to create an external javascript and an external css file for date picker and how to use it in eclipse
- Cross-Browser optimization for HTML/CSS
- Issue creating a Form with steps / groups
- Adding additional data to Raphael.js text element
- Split value into percentage with a slider
- Undefined is not a function with a combobox
- Looping Divs (jQuery Carousel)
- Error (net::ERR_EMPTY_RESPONSE) on AJAX call
- loading GIF image while navigating
- Making a Web Banner Responsive
- Function swipeleft / swiperight
- Need Toggle button in menu in both desktop and mobile version in bootstrap
- waypoints in google maps api shows error
- Button Click Affect Parent, But Not the Whole Class
- Parallax effect refresh rate in IE is horrible
- load static html when click bootstrap menu botton
- Call JS method from Razor form submit
- Jquery position() method get different value in chrome and safari
- Spring MVC JSP Jquery call controller method on button click post redirect error
- asp.net mvc remote validation in a Kendo window in IE
- Hover on text to show a tag title
- Avoid go to link of block element while clicking on link inside
- Can't append options to <select> with jQuery andajax data
- Display client machine date and time with timezone in browser
- FPDF, Yii and jQuery not working
- Sending form data with ajax echo data with php not displaying