Parse JSON from array and objects to HTML table - html

I have a MySQL db having columns "Name" "Service" "Cost" the output in JSON gives me like this:
"report": [{
"Name": "John",
"Service": "Hands",
"Cost": "200"
}]
}
I want to be able to convert this to a html table. I have tried this:
$(document).ready(function () {
var json = url;
var tr;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + report.json[i].Name + "</td>");
tr.append("<td>" + report.json[i].Service + "</td>");
tr.append("<td>" + report.json[i].Cost + "</td>");
$('table').append(tr);
}
});
But is not working, simply because i'm don't exactly know what I'm doing :)
Can someone help me?
Thanks!

$(function() { //equivalent to $(document).ready(...
$.getJSON(url,function(data) {
var report=data.report;
// your code here
});
});
Read about getJSON and ajax.

Related

Parsing and displaying JSON data

I am looking to display the data from my JSON file. The data I would like to display is the title from my JSON file however I am unsure of how to parse it. I think the part I am getting wrong is the 'data[i].archives.year1.title' etc but I am unsure of how to solve this.
This is what I have already tried:
My JSON file
[
{
"archives": {
"year1": {
"title": "Sample Title 1"
},
"year2": {
"title": "Sample Title 2"
},
"year3": {
"title": "Sample Title 3"
}
},
"collections": {
"health": {
"title": "Sample Title 4"
},
"money": {
"title": "Sample Title 5"
},
"relationships": {
"title": "Sample Title 6"
}
}
}
]
HTML
<div class="archives"></div>
<div class="collections"></div>
JavaScript file
fetch('example.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(error => console.log('Looks like there was a problem: ', error));
function appendData(data) {
var mainContainer = document.getElementById("archives");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML =
'<span class="archives">' + data[i].archives.year1.title + '</span>' +
'<span class="archives">' + data[i].archives.year2.title + '</span>' +
'<span class="archives">' + data[i].archives.year3.title + '</span>';
mainContainer.appendChild(div);
}
}
function appendData(data) {
var mainContainer = document.getElementById("collections");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML =
'<span class="collections">' + data[i].collections.health.title + '</span>' +
'<span class="collections">' + data[i].collections.money.title + '</span>' +
'<span class="collections">' + data[i].collections.relationships.title + '</span>';
mainContainer.appendChild(div);
}
}
I expect the output to display all of the titles from "archives" and all of the titles from "collections". I am new to JavaScript.
Your for loops here:
for (var i = 0; i < data.length; i++) //archives
for (var i = 0; i < data.length; i++) //collections
should be:
for (var i = 0; i < data.archives.length; i++) //archives
for (var i = 0; i < data.collections.length; i++) //collections
then you can reference values with:
div.innerHTML =
'<span class="archives">' + data.archives[i].year1.title + '</span>' +
'<span class="archives">' + data.archives[i].year2.title + '</span>' +
'<span class="archives">' + data.archives[i].year3.title + '</span>';
Also bonus points for looking into VueJS or ReactJS and also learning to use console.log in your browser's debug tools.
Edit:
After reading your comment and re-reading your JSON file I realize you have it nested inside an array. You can either delete the square brackets containing your object you intend to use, or use:
for (var i = 0; i < data[0].collections.length; i++)
'<span class="archives">' + data[0].archives[i].year1.title + '</span>'
The square brackets create an array containing the object you are trying to access, where you could append more objects, but since you're using an object of objects already the array containing it seems redundant.

How to create jQuery datatable with multiple child rows(nested table)?

Question:
I need to create a table with a nested table format. When a user clicks plus button it should show the nested table. If they click minus button it should hide.
I have done jquery datatable its working fine. but I'm not able to display multiple rows for child table. I have tried so many times I'm not able to display proper format.
This is the link I have referred to create a table
https://datatables.net/examples/api/row_details.html
Database:
Actual data coming from the database as per the below format and I have converted JSON format to display :
C# Code:
return new JsonResult { Data = new { data = test }, JsonRequestBehavior =
JsonRequestBehavior.AllowGet };
I need an output like this with a nested table:
UI CODE:
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-
left:50px;">'+
'<tr>' +
'<td>City Name</td>' +
'<td>Permission</td>' +
'</tr><tr>' +
'<td>' + d.City+ '</td>' +
'<td>' + d.Permission+ '</td>' +
'</tr>' +
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "UserName" },
{ "data": "Email" },
{ "data": "UserId" },
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
JSON FORMAT:
{"data":[
{"UserId":"ABC","UserName":"Peter","Email":"abc#gmail.com.com","CityName":"Chennai","Permission":"Manager,LocalUser"},
{"UserId":"ABC","UserName":"Peter","Email":"abc#gmail.com.com","CityName":"Bangalore","Permission":"Admin,LocalUser"},
{"UserId":"xyz","UserName":"Haiyan","Email":"abc2#gmail.com.com","CityName":"Bangalore","Permission":"LocalUser"},
{"UserId":"xyz","UserName":"Haiyan","Email":"abc2#gmail.com.com","CityName":"Chennai","Permission":"LocalUser,Manager"}]}
Technology used: ASP.Net MVC5
Any other way I'm ready to use either linq or modify JSON data format.
You can give Id to your child table like this
function format ( d ) {
// `d` is the original data object for the row
return '<table id="childtable" cellpadding="5" cellspacing="0" border="0" style="padding-
left:50px;">'+
'<tr>' +
'<td>City Name</td>' +
'<td>Permission</td>' +
'</tr><tr>' +
'<td>' + d.City+ '</td>' +
'<td>' + d.Permission+ '</td>' +
'</tr>' +
'</table>';
}
and do the same thing which you did for your parent table
var childTable = $('#childtable').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
],
"order": [[1, 'asc']]
} );
bind your json object in columns section.

Access specified attributes of Json for search index in cloudant

I have a Json document as:
{
"_id": "3de00db35e6549604c711e7295a1982a",
"_rev": "1-ecba71644d341dfe5cb9abf6dd13b23a",
"dateCreated": "2014-01-29 00:00:00",
"attributeCollection": {
"attributeArray": [
{
"updateable": false,
"lookup": "issuetype",
"issueAttributeDefinitionId": 13,
"attributeType": 1,
"name": "Web Type",
"value": [
"Improper Limitation of Authentication"
]
},
{
"updateable": true,
"lookup": "status",
"issueAttributeDefinitionId": 1,
"attributeType": 4,
"name": "Status",
"value": [
"Access with Right Permission"
]
}
]
},
"hash": "287030d6efa085b5b92b7106c0edb6d7"
}
I want to create search index for document using "name" and "value" ("name" or "value" only). I accessed these attributes by this codes:
for (var i=0; i<doc.attributeCollection.attributeArray.length; i++) {
if (doc.attributeCollection.attributeArray[i].name) {
name = doc.attributeCollection.attributeArray[i].name;
}
if (doc.attributeCollection.attributeArray[i].value) {
value = doc.attributeCollection.attributeArray[i].value;
}
}
It works when i use contentindex = name + " "+ value; the content shows "Web Type Improper Limitation of Authentication". However, if i use value only contentindex = value, it doesn't work, it shows null.
I know that the structure of "value" likes array (array with 1 element) and it doesn't have any attribute name.
How can i access the value properly?
Update:
When i index some cases as:
1. It works
var content=name + " " + value;
index("default", content);
2. It works
index("default", name);
3. It doesn't work
index("default", value);
4.I fixed with by revised the code to get "value" as:
if (doc.attributeCollection.attributeArray[i].value) {
for (var j=0; j<doc.attributeCollection.attributeArray[i].value.length; j++){
value = doc.attributeCollection.attributeArray[i].value[j];
}
}
Or
if (doc.attributeCollection.attributeArray[i].value) {
value = doc.attributeCollection.attributeArray[i].value[0];
}
It works with index("default", value);
However, when i used permutation function as discussed in this post
5. It works
var content= permuteword(name);
for(var k=0; k<content.length; k++){
index("default", content[k], { store : true });
}
6. It doesn't work
var content= permuteword(value);
for(var k=0; k<content.length; k++){
index("default", content[k], { store : true });
}
7. It doesn't work
var content=name + " " +value;
var content1= permuteword(content);
for(var k=0; k<content1.length; k++){
index("default", content1[k], { store : true });
}
I'm not exactly sure I completely understand your question. It sounds like you are creating an index like this:
for (var i=0; i<doc.attributeCollection.attributeArray.length; i++) {
if (doc.attributeCollection.attributeArray[i].name) {
name = doc.attributeCollection.attributeArray[i].name;
}
if (doc.attributeCollection.attributeArray[i].value) {
value = doc.attributeCollection.attributeArray[i].value;
}
index("contentindex", name + " " + value);
}
If this is the case you could try indexing the name and value separately (Update: changed to access each element in the value array):
for (var i=0; i<doc.attributeCollection.attributeArray.length; i++) {
if (doc.attributeCollection.attributeArray[i].name) {
name = doc.attributeCollection.attributeArray[i].name;
index("contentindex", name);
}
if (doc.attributeCollection.attributeArray[i].value) {
for (var j=0; j<doc.attributeCollection.attributeArray[i].value.length; j++) {
value = doc.attributeCollection.attributeArray[i].value[j];
index("contentindex", value);
}
}
}
Then querying by either the name or the value should return the correct result.
Please let me know if I am misunderstanding you question.

Trouble build a table from json file under a div

I need to get rather complicate JSON data from (large) JSON file into a table at a specific part of a page. Somehow when I ran my code, nothing happens.
Snap shoot of purchase.json file -
{
"table": {
"purchases": [
{
"First Name": "Joe",
"Last Name": "Jenson",
"Product": "Netbook Computer",
"Price": "356",
"Purchase Date": "04/04/2011",
"Unit Count": "1",
"Type": "Computer",
"Return Date": "05/03/2011",
"Seq. No.": "0"
},
{
"First Name": "Christy",
"Last Name": "Davis",
"Product": "iPad",
"Price": "656",
"Purchase Date": "04/07/2011",
"Unit Count": "1",
"Type": "Computer",
"Return Date": "05/06/2011",
"Seq. No.": "10"
},
{
"First Name": "Justin",
"Last Name": "Gill",
"Product": "Laptop Computer sleeve",
"Price": "699",
"Purchase Date": "04/02/2011",
"Unit Count": "1",
"Type": "Computer Assesory",
"Return Date": "05/01/2011",
"Seq. No.": "20"
}
]
}
}
The html file -
JSON to table
get json file "purchase.json"
Parse the array into a table and load it in AJAXDiv
Table header has to be pulled from the key in the key:value pair found in the JSON.
The JavaScript code I have is -
$(document).ready(function() {
//Retrieve the JSON data from the server using AJAX
$('#AJAXButton').click(function() {
$.getJSON('data/purchase.json', function(data) {
processJSON(data);
});
});
//Process and display the JSON data
function processJSON(jsondata) {
var output = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"><thead><tr>';
// retrieve the keys and place into an array
var keys = objKeys(jsonData.table.loans[0]).join("|");
var keyData = splitString(keys);
// print header
for (var i = 0; i < keyData.length; i++)
{
output += "<th>" + keyData[i] + "</th>";
}
output += "</thead></tr><tfoot>";
// print footer
for (var i = 0; i < keyData.length; i++)
{
output += "<th>" + keyData[i] + "</th>";
}
output += "</tfoot></tr><tbody>";
// print content of the json array in tbody
for(var j=0, jj = jsonData.table.loans.length; j < jj; j++)
{
for (var k = 0, kk = keyData.length; k < kk; k++)
{
var current = keyData[k];
output +="<td>" + jsonData.table.loans[j][current] + "</td>";
}
output += "</tr>";
}
output += "</tbody></tr></table>";
//Loop through the Languages
$('#AJAXDiv').html(output);
}
// get json keys
function objKeys(obj)
{
var keys = [];
var i = 0;
for (var z in obj)
{
if (obj.hasOwnProperty(z)) {
keys[i++] = z;
}
}
return keys;
}
// split string into array
function splitString(myString)
{
var mySplitResult = myString.split("|");
return mySplitResult;
}
});
It may be that you have a variable missing, there's
function processJSON(jsondata)
But you later use
jsonData.table.loans[0] //etc....
I suggest using a debugger like Firebug or DevTools, it makes problems like this much easier to catch.
You can also use this library: Json-To-Html-Table
I use this script that i coded my self, it really builds any json table from a mysql result
o whatever the MySQL is outputting, you can rename the column names with your own labels, by the output order. Also if you give none, the default names will be generated.
It used the $post Jquery plugin-in which you can add easly with 1 line of code.
all you need is the div with table_result:
function dyna_query(label){
$.post("your_mysql_query.php",{post_limit:15},function(e){
if(e=="fail"|| e=="" ||e=="[]"){return;}
var obj=JSON.parse(e);
//get default column names based on the associative object JSON
var column_n=Object.keys(obj[0]).length/2;
var c_names=Object.keys(obj[0]).splice(column_n,column_n);
//if there are labels, then these will replace others.
if( label){c_names=label.split(",");}
var table_row="";
//initialize table
var table_format="<table border=0><tr>";
for(var r=0; r<c_names.length;r++){
table_row+="<td class=table_h>"+c_names[r]+"</td>";}
table_row+="</tr>";
for(var i=0; i<obj.length;i++){table_row+="<tr>";
for(var c=0; c<c_names.length;c++){table_row+="<td class='table_bb'>"+obj[i][c]+" </td>";}table_row+="</tr>";}
//get all the other fields and rows
table_format+=table_row+"</table>";
//buld the html for the div with the id table_result
$("#table_result").html(table_format);
});
}
now simply call dyna_query("c1, c2, c3"); //renames default column names
or
dyna_query(); for full output with default labels

Graph API - FB - Getting crazy already. :s - Getting profile pictures

I can get the profile pictures from this:
data": [
{
"id": "11111111111_22222222222",
"from": {
"name": "Some Name",
"category": "Non-profit organization",
"id": "11222131212211"
},
I'm doing like so:
$.each(json.data,function(i,fb){
html += "<img id=\"image"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
}
No problems.
However, later on the graph I have:
"id": "11111111111_2222222222",
"to": {
"data": [
{
"name": "Some Name",
"category": "Non-profit organization",
"id": "11222131212211"
And I need to grab this id but I've tried:
alert(fb.to.data.id); got nothing.
If I do: alert(fb.to) I got "undefined".
Has anyone had this sort of problems or similar. As you may notice I'm not at all versatle onto programing matters, however, I will do my best to solve this issue.
1) How can I display the profile image on the second case?
2) How can I say: use the fb.from.id only when the graph has that.
About 2), please note that if I comment the line:
//html += "<img id=\"image"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
no images will be show and all post information (except the profile picture) is displayed on the viewport.
If I deal only with the first part of this graph (the one with "from:") I get the picture for that post.
SO, the issue must be, indeed, on the second graph part. The one with the "to:" that I can't grab the ID.
I've tried, as well, to avoid rendering the image on the second case but, at least run the first one. No luck at all.
if (fb.from.id != undefined) {
//do something;
}
The second part of the graph still returns an error.
With all this mess, that I can re-arrange, can I please ask your help. :S
**
Update:
**
The js code:
function fbFetch(){
var url = "https://graph.facebook.com/125120007543580/feed&callback=?&limit=2";
var i = 0;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<div id=\"faceWall\">";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
var idTotal = fb.id;
var ids = idTotal.split("_");
var href = "http://www.facebook.com/"+ids[0]+"/posts/"+ids[1];
var msg = fb.message;
//adicionado
if (msg == undefined) {
msg = 'Cick here to see the post title';
} else if (msg.length > 150) {
msg = msg.substr(0,200)+"...";
}
//ISSUE HERE. IF I COMMENT THIS LINE ALL GOES WELL BUT NO PROFILE PICTURES ARE DISPLAYED.
html += "<img id=\"imagem"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
html += "<div id=\"textoFaceWall\">";
html += "<p id=\"msg"+i+"\">";
//adicionado fb.name em vez de fb.from.name:
if (fb.name == undefined) {
html += "" + fb.from.name + " - " + msg + "</p>";
} else {
html += "" + fb.name + " - " + msg + "</p>";
}
html += "<p class=\"dataPostWall\" id=\"data"+i+"\">"+ dataFinal + "</p> ";
html += "</p>";
html += "</div>";
html += "<img class=\"linhaHomePageCanais\" src=\""+baseUrl+"/lib/img/linhaWall.png\" alt=\"linha wall\"/>";
});
html += "</div>";
$("#coluna2").append(html);
});
};
fbFetch();
And part of the graph:
({
"data": [
{
"id": "125120007543580_150880001634837",
"from": {
"name": "Some Name",
"category": "Non-profit organization",
"id": "125120007543580"
},
{
"id": "125120007543580_111122368963254",
"to": {
"data": [
{
"name": "Some Name",
"category": "Non-profit organization",
"id": "125120007543580"
}
]
},
I need to display the profile from fb.to.data.id,
I now notice, however, that data has [ instead of {, and that could mean that, in order to access id, I need to use another syntax perhaps?
Since the to parameters can holds more that one user, it's an array of objects. So you need to loop over that too:
if(fb.to) {
$.each(fb.to.data, function(j,to_user) {
// now you access it to_user.id
});
}
If you only want to show the first profile picture then use fb.to.data[0].id.
EDIT:
Okay, based on your comments and updated, here is your code with a working approach:
function fbFetch(){
var url = "https://graph.facebook.com/125120007543580/feed&callback=?&limit=2";
var i = 0;
//Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
$.getJSON(url,function(json){
var html = "<div id=\"faceWall\">";
//loop through and within data array's retrieve the message variable.
$.each(json.data,function(i,fb){
var idTotal = fb.id;
var ids = idTotal.split("_");
var href = "http://www.facebook.com/"+ids[0]+"/posts/"+ids[1];
var msg = fb.message;
//adicionado
if (msg == undefined) {
msg = 'Cick here to see the post title';
} else if (msg.length > 150) {
msg = msg.substr(0,200)+"...";
}
//ISSUE HERE. IF I COMMENT THIS LINE ALL GOES WELL BUT NO PROFILE PICTURES ARE DISPLAYED.
if(fb.from)
html += "<img id=\"imagem"+i+"\" src=\"http://graph.facebook.com/" + fb.from.id + "/picture\"/>";
if(fb.to) {
$.each(fb.to.data, function(j,to_user) {
html += "<img id=\"imagem"+i+"-"+j+"\" src=\"http://graph.facebook.com/" + to_user.id + "/picture\"/>";
});
}
html += "<div id=\"textoFaceWall\">";
html += "<p id=\"msg"+i+"\">";
//adicionado fb.name em vez de fb.from.name:
if (fb.name == undefined) {
html += "" + fb.from.name + " - " + msg + "</p>";
} else {
html += "" + fb.name + " - " + msg + "</p>";
}
html += "<p class=\"dataPostWall\" id=\"data"+i+"\">"+ dataFinal + "</p> ";
html += "</p>";
html += "</div>";
html += "<img class=\"linhaHomePageCanais\" src=\""+baseUrl+"/lib/img/linhaWall.png\" alt=\"linha wall\"/>";
});
html += "</div>";
$("#coluna2").append(html);
});
};
fbFetch();
You may try this for PHP
$request_url = 'http://graph.facebook.com/redbull/picture?redirect=false';
$requests = file_get_contents($request_url);
$fb_response = json_decode($requests);
$imagen[]=$fb_response->data->url;
There you get the URL of the picture from the URL item in the JSON Graph api call.