Trying to parse JSON objects to HTML table - javascript

I am using a jquery method to load JSON objects from the database. Then, I would want to display the record row by row in a HTML table. As can be seen in my JS file, I have tried to use a for and for each loop to loop through the data records but none of them are working apparently. My table seems to not display anything on the table or even error on result/ console log. However, there are data in my network log.
The json record in the network log is:
data: [
0:{
"id": "1",
"name": "John",
"type": "Client"
},
1:{
"id": "2",
"name": "Damen",
"type": "Agent"
},
2:{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
The HTML page is:
<table id="report" class="table table-bordered table-striped table-hover js-basic-example dataTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
app.viewReport();
</script>
My JS page is:
viewReport : function() {
$.ajax({
url: "/FIS/back-api/client/transaction/view",
dataType: "json",
method : 'GET',
success : function(data){
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].id+ "</td>");
tr.append("<td>" + data[i].name+ "</td>");
tr.append("<td>" + data[i].type+ "</td>");
$('#report tbody').append(tr);
}
}
/*$.each(data,function(i,item){
$('#report tr.odd').remove();
$("#report tbody").append(
"<tr>"
+"<td>"+item.id+"</td>"
+"<td>"+item.name+"</td>"
+"<td>"+item.type+"</td>"
+"</tr>" )
})
}*/
})
},

John , your JSON is invalid , this is the closest valid JSON i prepared from sample you shared above :
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
Notice that for an array of objects 0 : {} format is invalid, so when you query it in a loop you're not receiving any result.
Incorrect :
0:{
"id": "1",
"name": "John",
"type": "Client"
}
Correct :
{
"id": "1",
"name": "John",
"type": "Client"
}
How to validate your JSON
Following sites will help you verify your json :
jsonlint
jsoneditoronline
Answer
Re-generate your JSON and then proceed as indicated in other answers.
Also , i would advice against parsing the result as string ! In my humble opinion, the proper way to do this is to return a valid json from Backend/server

Your data array is having keys, which is incorrect json format, If its an array it should look like:
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]

Process your JSON data correctly like Winnie said in another answer of this question. Then you have not defined table row correctly.
for (i = 0; i < data.length; i++) {
$('#report tbody').append(
$('<tr>').append(
$('<td>').text(data[i].id),
$('<td>').text(data[i].name),
$('<td>').text(data[i].type)
)
);
}

try to append it like this
for (var i = 0; i < data.length; i++) {
var htm = '';
htm += '<tr>';
htm += "<td>" + data[i].id.toString() + "</td>";
htm += "<td>" + data[i].name.toString() + "</td>";
htm += "<td>" + data[i].type.toString() + "</td>";
htm += '</tr>';
$('#report tbody').append(htm);
}

var data = [{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
];
for (var i = 0; i < data.length; i++) {
var body = document.getElementById("tableBody");
var row = body.insertRow();
for (var item in data[i]) {
var cell = row.insertCell();
cell.innerHTML = data[i][item];
}
}
<html>
<body>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>

Related

Crossmatch two JSON files with the same values but different name to make a table from the two

I want to create a table build from two different JSON files. One of them shows me the names, work position, and age. The other shows me emails, name and also their work occupation. However, they have different names for the same values and are in different order. I used mustache.js to render the data, but I noticed the files have different order, so the names did not match the emails, as I build my table from fetching the two different files.
var text = '[
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
]'
var text2 = '[
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
var obj2 = JSON.parse(text2);
$(document).ready(function() {
var template2 = $('#user-template2').html();
for(var i in obj2)
{
var info = Mustache.render(template2, obj2[i]);
$('#ModuleUserTable2').html(info);
}
});
<table border="1" id = "ModuleUserTable">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Age</th>
</tr>
</table>
<script id="user-template" type="text/template">
<tr>
<td>{{name}}</td>
<td>{{occupation}}</td>
<td>{{age}}</td>
</tr>
</script>
<table border="1" id = "ModuleUserTable2">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Email</th>
</tr>
</table>
<script id="user-template2" type="text/template">
<tr>
<td>{{id}}</td>
<td>{{position}}</td>
<td>{{Email}}</td>
</tr>
</script>
I want to combine the data, so I can have all values in one table. So I have name, age, work, and email in one. I also have a 3rd Json from witch I can get their names only, but in the file the name of it is also different and it is only the value that is the same so it looks like "user135":"Jeff". I was thinking of doing something like this, but I do not know how to do it right:
function(nameuser)
for (var name) {
if(name."user135 == "Jeff"){
jQuery( Mustache.render($('#ModuleUserTable').html(), name)).appendTo("#ModuleUserTable2");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
This code will complete the first list items from second list via matching id and name properties. You can explore the result situation of list1 inside of the table;
var list1 = [
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
];
var list2 = [
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
];
function findSource(name){
let temp = null;
$(list2).each((index,object)=>(temp==null && object.id == name) ? temp=object : 0);
return temp;
}
function complete(object){
let source = findSource(object.name);
if(source!=null&&source!=undefined){
object.position = source.position;
object.Email = source.Email;
}
}
function addToTable(object){
let tr= $("<tr>");
$(tr).append("<td>" + object.occupation + "</td>");
$(tr).append("<td>" + object.name + "</td>");
$(tr).append("<td>" + object.age + "</td>");
$(tr).append("<td>" + object.position + "</td>");
$(tr).append("<td>" + object.Email + "</td>");
$("#ModuleUserTable2").append(tr);
}
$(list1).each((index,item)=>{
complete(item);
addToTable(item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id = "ModuleUserTable2">
</table>

jquery json showing undefined with html table parsing

I want to show below json data on html table.how can i show to html table when i try to show with below code its show mae undefined
[
{
"Key": "data",
"Value": [
[
{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [
{
"Key": "cursors",
"Value": [
{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}
]
}
]
Below is my Code and its show me undefined
success: function (data) {
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='prtoducttd'>" + item.ID + "</td>"
+ "<td class='prtoducttd'>" + item.Message + "</td>"
+ "</tr>";
$('#tblPost tbody').append(rows);
});
}
what is generic method to parse the json and show it to html table?
Out put
id message created_time
116312453556631_122404992947377 "My message" "2020-09-27T21:38:10+0000"
Check if item.Key == "data". If it is, loop through item.Value to get the values for that row.
var data = [{
"Key": "data",
"Value": [{
"Key": "created_time",
"Value": "2020-09-27T21:38:10+0000"
},
{
"Key": "message",
"Value": "My message"
},
{
"Key": "id",
"Value": "116312453556631_122404992947377"
}
]
},
{
"Key": "paging",
"Value": [{
"Key": "cursors",
"Value": [{
"Key": "before",
"Value": ""
},
{
"Key": "after",
"Value": ""
}
]
}]
}
];
$.each(data, function(i, item) {
if (item.Key == "data") {
let id, message, created;
$.each(item.Value, function(j, obj) {
switch (obj.Key) {
case 'id':
id = obj.Value;
break;
case 'message':
message = obj.Value;
break;
case 'created_time':
created = obj.Value;
break;
}
});
debugger;
let rows = "<tr>" +
"<td class='prtoducttd'>" + id + "</td>" +
"<td class='prtoducttd'>" + message + "</td>" +
"<td class='prtoducttd'>" + created + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPost">
<thead>
<tr>
<th>ID</th>
<th>Message</th>
<th>Created Time</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Make sure you're getting the data correctly first
For example, at item[0] see if the scope chain shows object available. Use the debugger and console to look through the data structure to follow the scope chain. Then write a loop once you've got the item and i correctly.
$.each(data, function (i, item) {
for (i = 0; i < item.Value.length; i++) {
let rows = "<tr>" +
"<td class='prtoducttd'>" + item.Value[i][2].Value + "</td>" +
"<td class='prtoducttd'>" + item.Value[i][1].Value + "</td>" +
"<td class='prtoducttd'>" + formatDate(new Date(item.Value[i][0].Value)) + "</td>" +
"</tr>";
$('#tblPost tbody').append(rows);
}
});

Issue Looping through an array of Objects dynamically using Javascript

Working on a Laravel application whereby am fetching data from the frontend and populating
dynamically on the frontend using Javascript. On the frontend I have partitioned in 2 major columns (left column and right column). On the left column there is a link which when hovered over or clicked the respective policies display on the right side.
The problem is am finding it quite difficult to iterate the policies array which contains a collection of Javascript objects and display them dynamically in the table.
When I use the method below I get [object Object] in the table body
asm variable from the backend
"agency_sales": [
{
"id": "111",
"policies": [
{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
},
]
}
{
"id": "222",
"policies": [
{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
},
]
}
]
Left column containing the link with a dynamic id
<div class="col-md-4">
#foreach($asm as $a)
Agency Sales Managers ID : {{ $a['id'] }}
#endforeach
</div>
Right column containing the table I would like to populate dynamically
<div class="col-md-8">
<table class="table table-hover mg-b-0 tx-11" id="summary-table">
<thead>
<tr>
<th>NAME</th>
<th>SUM</th>
<th>DATE</th>
</tr>
</thead>
<tbody>
<tr> <!-- Add policies dynamically via JS under respective thead columns--></tr>
</tbody>
</table>
</div>
JavaScript Code
$( document ).ready(function() {
var asmData = {!! json_encode($asm) !!};
});
$(document).on("mouseenter", "a", function() {
//Make sure table is empty
$('#summary-table tbody tr').html('');
//Execute ASM
var asmPolicies = '';
//Fetch id of a tag in the DOM
var asmId = $(this).attr('id');
for(var i = 0; i < asmData.length; i++) {
if(asmId == asmData[i]['id']) {
for(var j = 0; j < asmData[i]['policies'].length; j++){
asmPolicies += '<tr><td>' + asmData[i]['policies'][j] + '</td></tr>';
}
}
}
//append asmPolicies Html to the table
$('#summary-table tbody tr').append(asmPolicies);
//END ASM
});
Several issues - the main ones are
faulty JSON
not parsing the object
appending trs to trs instead of the tbody
Note the use of data attribute on the link
const asmData = [{
"id": "111",
"policies": [{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
}
]
}, {
"id": "222",
"policies": [{
"name": "JOHN DOE 3",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 4",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
}
]
}]
$(document).on("mouseenter", "a", function() {
var $tb = $('#summary-table tbody');
//Make sure table is empty
$tb.empty()
var asmId = $(this).attr('data-id'),
asmPolicies = "";
for (var i = 0; i < asmData.length; i++) {
if (asmId == asmData[i]['id']) {
for (var j = 0; j < asmData[i]['policies'].length; j++) {
var pol = asmData[i]['policies'][j];
asmPolicies += '<tr><td>' + pol.name + '</td><td>' + pol.sum_covered + '</td><td>' + pol.date + '</td><td>' + '</td></tr>';
}
}
}
//append asmPolicies Html to the table
$tb.append(asmPolicies);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
111 | 222
<div class="col-md-8">
<table class="table table-hover mg-b-0 tx-11" id="summary-table">
<thead>
<tr>
<th>NAME</th>
<th>SUM</th>
<th>DATE</th>
</tr>
</thead>
<tbody>
<tr>
<!-- Add policies dynamically via JS under respective thead columns-->
</tr>
</tbody>
</table>
</div>

Javascript Datatables generating HTML link using render function on JSON data

I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );
Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/

JSON nested Parsing Help using $.each

Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};

Categories

Resources