Convert json data to a html table
Thanks all for your replies. I wrote one myself. Please note that this uses jQuery.
Code snippet:
var myList = [ { "name": "abc", "age": 50 }, { "age": "25", "hobby": "swimming" }, { "name": "xyz", "hobby": "programming" }];
// Builds the HTML Table out of myList.function buildHtmlTable(selector) { var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) { var row$ = $('<tr/>'); for (var colIndex = 0; colIndex < columns.length; colIndex++) { var cellValue = myList[i][columns[colIndex]]; if (cellValue == null) cellValue = ""; row$.append($('<td/>').html(cellValue)); } $(selector).append(row$); }}
// Adds a header row to the table and returns the set of columns.// Need to do union of keys from all records as some records may not contain// all records.function addAllColumnHeaders(myList, selector) { var columnSet = []; var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) { var rowHash = myList[i]; for (var key in rowHash) { if ($.inArray(key, columnSet) == -1) { columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } $(selector).append(headerTr$);
return columnSet;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')"> <table id="excelDataTable" border="1"> </table></body>
convert JSON with html table tag using JavaScript
The problem is that your row
s don't have a property called "headerProperty". I think you are wanting to use the value inside headerProperty[j]
as a dynamic property name?
For that you have to use "bracket notation" to write the property accessor - this allows you to use any string value as the property name at runtime:
data.root.row[i][propertyHeader[j]]
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors for a bit more info.
Demo - I hope this now outputs what you expected:
var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'var data = JSON.parse(value);
var tablearray = [];tablearray.push("<table><tr>")var queryRow = data.root.row.length;
var headerProperty = Object.keys(data.root.row[0]);
for (i = 0; i < headerProperty.length; i++) { tablearray.push("<th>" + headerProperty[i] + "</th>");}tablearray.push("</tr>");//console.log(tablearray);
for (i = 0; i < queryRow; i++) { tablearray.push("<tr>") for (j = 0; j < headerProperty.length; j++) { // console.log(headerProperty[j]); // console.log(data.root.row[0].DatabaseID); // console.log(data.root.row[i].headerProperty[j]); tablearray.push("<td>" + data.root.row[i][headerProperty[j]] + "</td>"); } tablearray.push("</tr>");}tablearray.push("</table>");document.write(tablearray.join(''));
Create HTML Table Using JSON data in JavaScript
You got a couple of problems, but not with the CORS, you got the results from the request. The error came from the createTableFromJSON
function.
The main problems:
- Forgot to add
("table")
aftercreateElement
- Two unnecessary loops
- Wrong use of the JSON to get the
Name
- More
tr
than needed
Working code:
// Create XMLHttpRequest object.const proxyurl = "https://cors-anywhere.herokuapp.com/";const url = "https://www.encodedna.com/library/sample.json";fetch(proxyurl + url) .then(response => response.text()) .then(contents => createTableFromJSON(contents)) .catch((e) => console.log('error'))
// Create an HTML table using the JSON data.function createTableFromJSON(jsonData) { var arrBirds = []; arrBirds = JSON.parse(jsonData); // Convert JSON to array.
var col = []; for (var key in arrBirds) { if (col.indexOf(key) === -1) { col.push(key); } }
// Create a dynamic table. var table = document.createElement("table") // Create table header. var tr = table.insertRow(-1); // Table row. (last position)
for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); // Table header. th.innerHTML = col[i]; tr.appendChild(th); }
tr = table.insertRow(-1); // add new row for the names // Add JSON to the table rows. for (var i = 0; i < arrBirds.length; i++) { var tabCell = tr.insertCell(-1); tabCell.innerHTML = arrBirds[i].Name; }
// Finally, add the dynamic table to a container. var divContainer = document.getElementById("showTable"); divContainer.innerHTML = ""; divContainer.appendChild(table);};
* { font: 17px 'Segoe UI';}
table,th,td { border: solid 1px #ddd; border-collapse: collapse; padding: 2px 3px; text-align: center;}
th { font-weight: bold;}
<h3> Data extracted from External JSON file and converted to an HTML table</h3><div id='showTable'></div>
Converting a JSON data output to a HTML-TABLE format in Python - Flask?
Your data_all
is a list of lists. If you pass a list of dicts to json2html
it will format it as an HTML table for you.
For example:
data_all = []
for item in result:
data_all.append({
"Name": item["trail name"],
"Description": item["description"]
})
Then you can pass this list to json2html
:
html_data = json2html.convert(json=data_all)
The resulting HTML will be in the following format:
<table border="1">
<thead>
<tr><th>Name</th><th>Description</th></tr>
</thead>
<tbody>
<tr>
<td>Upper Yosemite Falls</td>
<td>Upper Yosemite Falls Trail ...</td>
</tr>
<tr>
<td>Vernal and Nevada Falls via the Mist Trail</td>
<td>Vernal and Nevada Falls via the Mist Trail is a 6.4 mile ...</td>
</tr>
</tbody>
</table>
How to convert JSON String to HTML Table in Flask?
As I have checked above, try this
d5 = ['{"pf":"K", "users":1, "events":1},{"pf":"A", "users":7, "events":7},{"pf":"I", "users":3, "events":3}']
# convert spark json array result to a list.
finalJson = json.loads("[" + d5[0] + "]")
return render_template_string('''
<style>
table, th, td {
border: 1px solid black;
}
table {
width:80%;
border-collapse: collapse;
}
td {
text-align: center
}
th:first-child, td:first-child {
text-align: left
}
th:last-child, td:last-child {
text-align: right
}
</style>
<table>
<tr>
<th> PF </th>
<th> users </th>
<th> events </th>
</tr>
{% for row in table_data %}
<tr>
<td>{{ row['pf'] }}</td>
<td>{{ row['users'] }}</td>
<td>{{ row['events'] }}</td>
</tr>
{% endfor %}
</table>
''', table_data=finalJson)
You could also feel free to modify styles to what you want.
How can I convert this json data to html table with javascript?
Since your object is not flat, you cannot truly render it all to table. You have to make a decision about the nested objects. Below I am simply using json.stringify to show those objects in a table cell. You should of course handle this according to your needs.
const data = [ { "1": [ { Time: "01:35 AM", Location: "dhaka bangladesh", "BUS Detail": { air_Logo: "logo goes here", air_Name: "Airbus" }, busNo: "AK119", arrTime: "05:40 AM", "arrival Loc": "barisal" } ] }];
const base = data[0]["1"];
const table = document.createElement("table");const thead = table.createTHead();const tbody = document.createElement("tbody");table.append(tbody)
const headRow = thead.insertRow();const headers = Object.keys(base[0]).forEach((head) => { let cell = headRow.insertCell(); cell.textContent = head;});
base.forEach((obj) => { const row = tbody.insertRow(); const vals = Object.values(obj); vals.forEach((v) => { const cell = row.insertCell(); if (typeof(v) !== 'string') { return cell.textContent = JSON.stringify(v); } cell.textContent = v });});
document.body.append(table)
convert json to html table using jquery
Assuming you have a well-formatted JSON file, you can do It like this:
$(document).ready(function() { // $.getJSON(url, callback); $.getJSON('https://api.myjson.com/bins/aruak', function(json) { tableGenerator('#tableName', json); });});
function tableGenerator(selector, data) { // data is an array var keys = Object.keys(Object.assign({}, ...data));// Get the keys to make the header // Add header var head = '<thead><tr>'; keys.forEach(function(key) { head += '<th>'+key+'</th>'; }); $(selector).append(head+'</tr></thead>'); // Add body var body = '<tbody>'; data.forEach(function(obj) { // For each row var row = '<tr>'; keys.forEach(function(key) { // For each column row += '<td>'; if (obj.hasOwnProperty(key)) { // If the obj doesnt has a certain key, add a blank space. row += obj[key]; } row += '</td>'; }); body += row+'<tr>'; }) $(selector).append(body+'</tbody>');}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><table id="tableName"></table>
Related Topics
Why Don't Self-Closing Script Elements Work
Strip HTML from Text JavaScript
Return HTML Content as a String, Given Url. JavaScript Function
JavaScript Confirm Popup Yes, No Button Instead of Ok and Cancel
How to Increase Browser Zoom Level on Page Load
Trigger Change Event When the Input Value Changed Programmatically
How to Prevent a Click on a '#' Link from Jumping to Top of Page
Set Custom Html5 Required Field Validation Message
How to Calculate the Xpath Position of an Element Using JavaScript
How to Pass Parameters on Onchange of HTML Select
Including Both Href and Onclick to HTML ≪A≫ Tag
JavaScript Does Not Fire After Appending
What Are Cookies and Sessions, and How Do They Relate to Each Other
User Recognition Without Cookies or Local Storage
"Mixed Content Blocked" When Running an Http Ajax Operation in an Https Page