create dynamic JSON table HTML JS - javascript

My Sample JSON data looks something like:
the data fields are not the same set of fields for all my rows.
[{"date":"2020-04-05 18:26:01", "mydata":{"city":{"name":"paris"},"travel":{"frequency":"5","climate":"cold"}}},
{"date":"2020-04-05 18:26:17", "mydata":{"city":{"name":"amsterdam"},"fly":{"airports":"1","type":"international"}}}]
This is saved into a column in my MariaDB.
I want to retrieve this in a table format like:
Date mydata-city-name travel-frequency travel-climate fly-airports fly-type
2020-04-05 18:26:01 paris 5 cold null/blank null/blank
2020-04-05 18:26:17 amsterdam null/blank null/blank 1 international
so far i tried the below js and html
but im not able to get the data as expected:
Javascript:
var myList
$.ajax({
type: "GET",
url: "symptom_list.php",
success: function (data) {
console.log(data)
myList = JSON.parse(data)
console.log(JSON.parse(
data)
);
/* alert(data); */ // show response from the php script.
},
});
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;
}
HTML:
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>
My output is rightnow:
Date mydata
2020-04-05 18:26:01 <blank>
2020-04-05 18:26:17 <blank>
how do i get my expected output?

If you have nested data structure you also have to traverse in nested elements
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 = getCellValue(myList[i], columns[colIndex]);
if (cellValue == null)
cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
recursiveHeaderCheck(rowHash, selector, "", columnSet, headerTr$);
}
$(selector).append(headerTr$);
return columnSet;
}
function recursiveHeaderCheck(ListElement, selector, parentKeyname, columnSet, headerTr$) {
if (typeof ListElement === 'object') {
if (parentKeyname != '')
parentKeyname = parentKeyname + '-';
for (var key in ListElement) {
var keyname = parentKeyname + key;
recursiveHeaderCheck(ListElement[key], selector, keyname, columnSet, headerTr$);
}
} else {
if ($.inArray(parentKeyname, columnSet) == -1) {
columnSet.push(parentKeyname);
headerTr$.append($('<th/>').html(parentKeyname));
}
}
}
function getCellValue(nestedStructure, columnHeader) {
var subElement = nestedStructure;
var subHeaders = columnHeader.split("-");
for (var k = 0; k < subHeaders.length; k++) {
if (typeof subElement === 'object' && subElement != null)
subElement = subElement[subHeaders[k]];
}
return subElement;
}

Related

Javascript: Add Class to TD on dynamically generated table based on server data

I have the below script that dynamically generates a table based on an array of objects that the server is feeding me that I got from Here (hopefully I got the anchor tag right, here should be a link).
// Builds the HTML Table out of myList json data from Ivy restful service.
function buildHtmlTable(myList) {
var columns = addAllColumnHeaders(myList);
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 = ""; }
\\This is where I want to put the code that compares cellValue and applies
\\the class
row$.append($('<td/>').html(cellValue));
}
$("#Jsontable").append(row$);
}
}
function addAllColumnHeaders(myList)
{
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));
}
}
}
$("#Jsontable").append(headerTr$);
return columnSet;
}
I cannot figure out how to add a class to each td based on comparing the value of cellvalue to a goal value where it is classed as .red if it is higher and .green if it is not. My comment in the above code is where I believe the if/then should appear, but my kung fu is no good here.
Something like:
row$.append($('<td/>').html(cellValue).addClass(cellValue > goal ? 'red' : 'green'));

Can I create dropdown rows dynamically for a table using html and Javascript

I've created a table dynamically, but now I want to create a dropdown row on demand. I have an onclick handler for each row. Upon clicking, this row should drop something downward (like a hidden div but unfortunately these cannot be easily created in a dynamic setting, as there's not a way to assign a unique id at row creation. Is this even possible in Javascript/jQuery? or, preferably, twitter bootstrap?
function buildHtmlTable(portalData, tablename) {
var columns = [];
var headerTr$ = $('<tr/>');
var n = 0;
if (tablename == "order-table") {
document.getElementById("dist-name").innerText = JSON.parse(JSON.stringify(portalData[0], null, 2))["Company Name"];
n = 1;
}
for (var i = 0 ; i < portalData.length ; i++) {
var rowHash = portalData[i];
for (var key in rowHash) {
if ($.inArray(key, columns) == -1) {
columns.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$('#' + tablename).append(headerTr$);
for (i = 0 ; i < portalData.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = n ; colIndex < columns.length ; colIndex++) { // n is how many columns to drop, based on table name
var cellValue = portalData[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$('#' + tablename).append(row$);
}
// Drop unnecessary columns
for(i = 0 ; i<n; i++) {
$("#order-table").find('td,th').first().remove();
}
if (tablename == "order-table") {
var tablerows = document.getElementsByTagName('tr');
for (var x in tablerows) {
tablerows[x].classList.add("clickable");
tablerows[x].setAttribute(data-toggle,"collapse");
tablerows[x].setAttribute(data-target,"");
}
}
}

How to populate the table using JSON and Javascript just below the row

I have to populate a table using JSON and Javascript but the data go to next row. Whereas I wish to have data just below the row of column header
Here is my json:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
The given code fills the data in this sequence :
column1 column2 column3
abc
25
xyz
But I wish to have it like :
column1 column2 column3
abc 25 xyz
Here is my code:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
$(document).ready(function ()
{
buildHtmlTable();
});
function buildHtmlTable()
{
var columns = addAllColumnHeaders(myList); // columns get the name of coluns
alert("test : " + myList);
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));
}
$("#excelDataTable").append(row$);
}
}
Edit
function addAllColumnHeaders(myList)
{
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));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
and
<table id="excelDataTable" class="contentpanel" border="1"></table>
Take var row$ = $('<tr/>'); out of the loop. No need for double loop. Try this:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
$(document).ready(function ()
{
buildHtmlTable();
});
function buildHtmlTable()
{
var columns = addAllColumnHeaders(myList); // columns get the name of coluns
//alert("test : " + myList);
var row$ = $('<tr/>');
var colIndex = 0;
for (var i = 0 ; i < myList.length ; i++)
{
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
$("#excelDataTable").append(row$);
colIndex++;
}
}
function addAllColumnHeaders(myList)
{
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));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}

read data from json file and create html file

Hello I am new for jquery and json file,I want to create html file from json file.first data read from .json file then on the basis of json object create html file my json data is :--
{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"5544F75A-4589-4605-B447-0AB123A1865D","parent_guid":"00000000-0000-0000-0000-000000000000","ElementName":"Main","elementtype":"Form","elementsource":"","onload":"","sequence":"0","isPublic":"0","attributes":{"width":"28%","height":"200px"}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"6EB6C873-E2EC-4515-A6D8-2FBF0119F573","parent_guid":"5544F75A-4589-4605-B447-0AB123A1865D","ElementName":"MainTab","elementtype":"tab","elementsource":"","onload":"","sequence":"0","isPublic":"0","attributes":{"width":"65%"}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"6E13FCBC-0DB2-4499-B200-61CD5A36F0C1","parent_guid":"6EB6C873-E2EC-4515-A6D8-2FBF0119F573","ElementName":"Results","elementtype":"tabdetail","elementsource":"","onload":"","sequence":"2","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"E5539403-9A58-4310-8013-AF4EEF62C217","parent_guid":"6EB6C873-E2EC-4515-A6D8-2FBF0119F573","ElementName":"Billing","elementtype":"tabdetail","elementsource":"","onload":"","sequence":"1","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"113293EE-0997-4398-8E4A-6BE7AEDC32C1","parent_guid":"6EB6C873-E2EC-4515-A6D8-2FBF0119F573","ElementName":"Utilities","elementtype":"tabdetail","elementsource":"","onload":"","sequence":"3","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"4EFA32EC-B37E-4DC2-A249-E7156196918F","parent_guid":"6E13FCBC-0DB2-4499-B200-61CD5A36F0C1","ElementName":"ResultsTab","elementtype":"tab","elementsource":"","onload":"","sequence":"0","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"F6FB6DAA-F6D9-43B0-88FD-688BEC0EAF32","parent_guid":"E5539403-9A58-4310-8013-AF4EEF62C217","ElementName":"BillingTabHeader","elementtype":"tab","elementsource":"","onload":"","sequence":"1","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"9E622E70-095A-4A1A-BA06-C67946D49549","parent_guid":"F6FB6DAA-F6D9-43B0-88FD-688BEC0EAF32","ElementName":"Current Billing","elementtype":"","elementsource":"","onload":"","sequence":"3","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"B41D9F7B-ED6F-47C5-8562-437D9F5F23AD","parent_guid":"F6FB6DAA-F6D9-43B0-88FD-688BEC0EAF32","ElementName":"Billing","elementtype":"","elementsource":"Sp_getBilling","onload":"","sequence":"1","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"151F6F13-C200-4EDA-8467-1D5AEB5F03A2","parent_guid":"F6FB6DAA-F6D9-43B0-88FD-688BEC0EAF32","ElementName":"PreBilling","elementtype":"","elementsource":"","onload":"","sequence":"2","isPublic":"0","attributes":{"":""}},{"userguid":"AB92DE99-D0D5-4081-802C-2E331F88AE84","sessguid":"AEA0774B-8CCE-4CB1-A6F8-484ADA1FB45F","transguid":"","ret_code":"ok","ret_mess":"","rec_guid":"91158CB4-C93B-4440-BAA4-771E9493EEA9","parent_guid":"F6FB6DAA-F6D9-43B0-88FD-688BEC0EAF32","ElementName":"Final Billing","elementtype":"","elementsource":"","onload":"","sequence":"4","isPublic":"0","attributes":{"":""}}
I tried this but this is not :-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div style="margin: 20px auto; width: 500px;">
<form border="1" cellpadding="5" id="jsonTable" style="border-collapse: collapse;">
</form>
</div>
<script type="text/javascript">
function addAllColumnHeaders(myList) {
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));
}
}
}
$("#jsonTable").append(headerTr$);
return columnSet;
}
$.getJSON("demo.json", function (data) {
var columns = addAllColumnHeaders(data);
for (var i = 0; i < data.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = data[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#jsonTable").append(row$);
}
});
I want to create html according to element type in JSON array. if like element type is form then html create form and if element type is tab then create tab.
for (var i = 0; i < data.length; i++) {
if (data[i].elementtype === "Form" {
//build form here
}
if (data[i].elementtype === "tab" {
var columns = addAllColumnHeaders(data);
//etc
}
}

Creating table from json in javascript using jquery for any field

I so far can view the json response. Now I wanted to convert them to tables. I am using the following code to parse data about weather of cities. I am trying to use the following code.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
var columns = addAllColumnHeaders(myList);
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));
}
$("#excelDataTable").append(row$);
}
}
);}
function addAllColumnHeaders(myList) {
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));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}​
</script>
</head>
<body>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>
</body>
</html>
I got the following result:
And in chrome, i can't even view that
The response I'm getting is an object not an array. Process the response as an object.
function goTo() {
$.getJSON("http://api.openweathermap.org/data/2.5/weather?key=api&format=json&q=" + link_id.value, function(result, status, jqXHR) {
var myList = (jqXHR.responseText);
myList = JSON.parse(myList);
console.log(myList);
var keys = [];
for (var key in myList) {
keys.push(key);
}
addAllColumnHeaders(myList, keys);
var row$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var cellValue = myList[key];
if (cellValue == null) {
cellValue = "";
} else if (typeof cellValue == "object") {
cellValue = JSON.stringify(cellValue);
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
});
}
function addAllColumnHeaders(myList, keys) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
headerTr$.append($('<th/>').html(key));
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2> Search box </h2>
<input type='text' id='link_id'>
<input type='button' id='link' value='Search' onClick='goTo()'>
<table id="excelDataTable" border="1" />
<div></div>

Categories