A.L. A.L. - 5 months ago 9
JSON Question

JSON formating when displaying in website

So I'm very(very) new to JSON and I can't understand how it works.

I have this function which displays the JSON in the website

function makeItem(data){
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}


I get that
k
and
v
are key and values but the function displays all the data from the JSON.

[{"ProductDataId":"132","ProductId":"20","FilterId":"40","ProductDataBG":"on","ProductDataEN":null},{"ProductDataId":"133","ProductId":"21","FilterId":"40","ProductDataBG":"on","ProductDataEN":null},{"ProductDataId":"134","ProductId":"22","FilterId":"40","ProductDataBG":"on","ProductDataEN":null}]


Let's say I want the dispalayed data(in the website) to be in different divs for the ProductDataId, ProductId etc(not in table as it is now).

The question is how to make that happen? I think that I should change something in
tbl_row += "<td>"+v+"</td>";
but I'm not sure if that will be the only change and how to get specific info(something like
v['ProductDataId']
?).

Thank you in advance!

Answer

You probably wouldn't do the 2nd $.each. Just access the object properties directly like so:

function makeItem(data){
    var tbl_body = "";
    $.each(data, function() {
        var tbl_row = "";

        tbl_row += "<td>"+this.ProductDataId+"</td>";
        tbl_row += "<td>"+this.ProductId+"</td>";

        tbl_body += "<tr>"+tbl_row+"</tr>";
    })
    return tbl_body;
}