How to convert json to html table - javascript

Hi I need to convert the following json into a html table
{
"condomini": [
{
"ricevute": [
{
"data": "31/10/2017",
"numero": "1715759",
"dettagli": "Contante",
"descrizione": "Versamento giuseppe rossi rata ottobre ",
"totale": "108,00",
"righe": [
{
"importoPagato": "5,00",
"importoCredito": "5,00",
"importoResiduo": "0,00",
"scala": "B",
"piano": "2",
"interno": "12",
"descrizione": "Contributo per riparazione cancello A"
},
{
"importoPagato": "103,00",
"importoCredito": "103,00",
"importoResiduo": "0,00",
"scala": "B",
"piano": "2",
"interno": "12",
"descrizione": "Rata ottobre - dicembre 2017"
}
]
}
]
}
]
}
So far this is what I’ve managed to do, but i don’t know how to render the array “righe”, if you put the json code into http://json2table.com/ then you have an idea how the table should look like.
$.ajax({
type: "json",
url: "../km-client-controllers/km-ctrl-client-ricevute.php",
success: function(result) {
datas = JSON.parse(result);
$('#nome_condominio').html(datas.condomini[0].condominio.nome);
$('#indirizzo_condominio').html(datas.condomini[0].condominio.indirizzo);
$.each(datas.condomini[0].ricevute, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.data),
$('<td>').text(item.numero),
$('<td>').text(item.descrizione),
$('<td>').text(item.totale)
).appendTo('#records_table');
});

I am not sure how you want your table to look, but to get the data inside the righe array you can do
$.each(item.righe ....)
similar to how you getting the data from the ricevute array.
See this fiddle for an example: http://jsfiddle.net/zs0yowhk/21

Related

Using JSON Array with AJAX

I'm trying to append parts of a JSON array (that is received from a server) to a table after clicking a button. Somehow I can't add the parts of the json array to this table.
This is the JSON Array received from the server:
{"pass": [
{
"Date":"01.01.2001",
"Time":"14:20",
"ID":"1234",
"Name":"Sat",
"elevation":"168.9°",
"losTime":"04:31"
},
{
"Date":"01.01.2002",
"Time":"14:30",
"ID":"1235",
"Name":"Com",
"elevation":"16.9°",
"losTime":"04:25"
}
]}
The Code is the following:
$(document).ready(function(){
$("#submit-button").click(function() {
$.ajax({
url: "../rest/passdata",
type: "GET",
data: {
satellite: document.getElementById("satellite").value,
startDate: document.getElementById("startDate").value,
startTime: document.getElementById("startTime").value,
endDate: document.getElementById("endDate").value,
endTime: document.getElementById("endTime").value
},
dataType: "json",
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(response) {
var arr = response;
$("#pd-table").find("#pd-body").empty();
$.each(arr, function(i, value){
var checkbox = $('<input type="checkbox"/>');
$("#pd-table").find("#pd-body")
.append($("<tr>"))
.append($("<td>").append(checkbox))
.append($("<td>").append(arr.pass.ID[i]))
.append($("<td>").append(arr.pass.Date[i]))
.append($("<td>").append(arr.pass.Time[i]))
.append($("<td>").append(arr.pass.losTime[i]))
.append($("<td>").append(arr.pass.Name[i]))
.append($("<td>").append(arr.pass.elevation[i]))
.append($("</tr>"))
The checkbox gets added to the table, which makes me think that reading out the array does not work the way it should.
I already tried to parse the response from the server but that also didn't work out and in that case even the checkbox didn't get added to the table.
I hope someone can help me out!
Several problems:
You want to loop over the array in response.pass not the whole object
You are appending the cells to the <tbody> not to the new row.
You can not append a closing tag. The DOM only accepts complete elements and has no understanding of appending a closing tag in a jQuery object. The full element gets created when you do $('<tagname>')
Simplified version:
var arr = response.pass;
var $tbody = $("#pd-body").empty();
$.each(arr, function(i, value) {
var checkbox = $('<input type="checkbox"/>');
var $row = $("<tr>")
// append cells to the new row
.append($("<td>").append(checkbox))
.append($("<td>").text(value.ID))
.append($("<td>").text(value.Date))
.append($("<td>").text(value.Time))
.append($("<td>").text(value.losTime))
.append($("<td>").text(value.Name))
.append($("<td>").text(value.elevation));
// append complete row
$tbody.append($row)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="pd-table" border=1>
<tbody id="pd-body">
</tbody>
</table>
<script>
var response = {
"pass": [{
"Date": "01.01.2001",
"Time": "14:20",
"ID": "1234",
"Name": "Sat",
"elevation": "168.9°",
"losTime": "04:31"
},
{
"Date": "01.01.2002",
"Time": "14:30",
"ID": "1235",
"Name": "Com",
"elevation": "16.9°",
"losTime": "04:25"
}
]
}
</script>

How can I replace outer object with an array?

I'm trying to make a graph. S I need to send an ajax request, select some rows from database, then return the result. I did it. And here is the output:
success : function (data) {
console.log(data);
}
To make that graph, I need to convert my current output to this structure: (this structure is the one I should pass it to the library which draws the graph)
var json = [
{
"adjacencies": [
{
"nodeTo": "graphnode15",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode16",
"nodeFrom": "graphnode0",
"data": {}
},
{
"nodeTo": "graphnode17",
"nodeFrom": "graphnode0",
"data": {}
}
],
"data": {
"$color": "#83548B",
"$type": "circle"
},
"id": "12",
"name": "sajad"
}
];
I've tested all of these:
console.log(data);
console.log([data]);
console.log(JSON.stringify(data));
console.log("["+JSON.stringify(data)+"]");
But none of them isn't expected structure for the library which draws the graph. Anyway, Does anybody know how can I make expected structure?
JSON.parse(data) will do this.
Try:
json =[]
json.push(data)
send this json to the graph
Maybe this should work
success : function (data) {
var json = [JSON.parse(data)];
console.log(json);
}

How to Get data in Json using javascripts?

Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.

Howto convert JSON to Array

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

how to use for each with mustache javascript?

i have some json objects and some of them have some other objects inside them.
if i leave only the json obj that don't have other obj inside them and then apply the template, everything goes well, i get, in this case 3 li elements.
but if i grab the original json obj the results are a bit wired. I believe i need to do a each statement to iterate through each sub json obj from inside each main one
maybe i am a bit confuse so here is some code.
i have some json data like this:
{
"msg_id":"134",
"message":"Nick",
"comment":[
{
"com_id":"9",
"comment":"test",
},
{
"com_id":"10",
"comment":"testtt",
},
{
"com_id":"11",
"comment":"testtttt",
}]
},
{
"msg_id":"134",
"message":"Nick",
},
{
"msg_id":"134",
"message":"Nick",
}
and i am trying to arive at something like this:
Nick
test
testtt
testtttt
Nick
Nick
i've created a template like this:
function messagesTamplate(data)
{
$.each(data, function(index, obj)
{
msg += template.replace( /{{message}}/ig , obj.message );
if(obj.comment) {
$.each(obj.comment, function(key, val)
{
msg += template.replace( /{{comment}}/ig , val.comment );
});
}
});
return msg;
}
then i just append this to the main ul.
thanks
data needs to be an array (see the enclosing [])
var data = [{
"msg_id": "134",
"message": "Nick",
"comment": [{
"com_id": "9",
"comment": "test",
}, {
"com_id": "10",
"comment": "testtt",
}, {
"com_id": "11",
"comment": "testtttt",
}]
}, {
"msg_id": "134",
"message": "Nick",
}, {
"msg_id": "134",
"message": "Nick",
}]
is just this in mustache templates:
{{#data}} //loop through all data
{{message}} //pick out the "message" per iteration
{{#comment}} //loop through all comments in an iterated item
{{comment}} //pick out the comment
{{/comment}}
{{/data}}

Categories

Resources