Parsing JSON objects for HTML table

232,854

Solution 1

Loop over each object, appending a table row with the relevant data each iteration.

$(document).ready(function () {
    $.getJSON(url,
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].User_Name + "</td>");
            tr.append("<td>" + json[i].score + "</td>");
            tr.append("<td>" + json[i].team + "</td>");
            $('table').append(tr);
        }
    });
});

JSFiddle

Solution 2

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","score":"30"},{"name": "name2","score":"50"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<div jput="tbody_template">
 <tr>
  <td>{{name}}</td>
  <td>{{score}}</td>
 </tr>
</div>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Solution 3

Loop over each object, push in string array and join them. Append in target table, it is better.

$(document).ready(function () {
$.getJSON(url,
function (json) {
    var tr=[];
    for (var i = 0; i < json.length; i++) {
        tr.push('<tr>');
        tr.push("<td>" + json[i].User_Name + "</td>");
        tr.push("<td>" + json[i].score + "</td>");
        tr.push("<td>" + json[i].team + "</td>");
        tr.push('</tr>');
    }
    $('table').append($(tr.join('')));
});

Solution 4

You can use KnockoutJS with jQuery. KnockoutJS have smart data-binding features. By using the foreach binding feature you can write your code like this example:

HTML:

<table>
    <thead>
        <tr>
            <th>User Name</th>
            <th>Score</th>
            <th>Team</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: teams">
        <tr>
            <td data-bind="text: User_Name"></td>
            <td data-bind="text: score "></td>
            <td data-bind="text: team "></td>
        </tr>
    </tbody>
</table>

JavaScript:

$(document).ready(function () {
        $.getJSON(url,function (json) {
               ko.applyBindings({
                  teams: json
               });
          }
        });

    });

Fiddle Demo with your dummy data

Solution 5

This one is ugly, but just want to throw there some other options to the mix. This one has no loops. I use it for debugging purposes

var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
var myStrObj = JSON.stringify(myObject)
var myHtmlTableObj = myStrObj.replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")

$('#myDiv').html(myHtmlTableObj)

Example:

    var myObject = {a:1,b:2,c:3,d:{a:1,b:2,c:3,e:{a:1}}}
    var myStrObj = JSON.stringify(myObject)
    var myHtmlTableObj = myStrObj.replace(/\"/g,"").replace(/{/g,"<table><tr><td>").replace(/:/g,"</td><td>","g").replace(/,/g,"</td></tr><tr><td>","g").replace(/}/g,"</table>")

    $('#myDiv').html(myHtmlTableObj)
#myDiv table td{background:whitesmoke;border:1px solid lightgray}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id='myDiv'>table goes here</div>
Share:
232,854
user2478342
Author by

user2478342

Updated on July 09, 2022

Comments

  • user2478342
    user2478342 almost 2 years

    I am trying to display a "leaderboard" table based on JSON data.

    I have read a lot about the JSON format and overcome some initial obstacles, but my Javascript knowledge is very limited and I need help!

    Basically my JSON data comes through looking like this:

    [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}]
    

    What I need is to be able to loop through this array, generating a table row or list item for each object. There will be an unknown amount of total objects in the array but each will have the same format- three values: Name, Score, Team.

    So far I have used the following code, which confirms that I am successfully loading the objects in the console-

    $.getJSON(url,
    function(data){
      console.log(data);
    });
    

    but I am not sure how to iterate over them, parsing them into the HTML table.

    The next step is sorting the entries by score in descending order...

    Any help would be much appreciated. Thanks!

    EDIT:

    Updated code below, this works:

    $.getJSON(url,
    function (data) {
        var tr;
        for (var i = 0; i < data.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + data[i].User_Name + "</td>");
            tr.append("<td>" + data[i].score + "</td>");
            tr.append("<td>" + data[i].team + "</td>");
            $('table').append(tr);
        }
    });
    

    (The $.parseJSON was not necessary, we can use 'data' as the JSON array is already parsed I believe)

  • user2478342
    user2478342 almost 11 years
    Thanks very much for your quick reply- this definitely puts me on the right track. However when I replace the value of the json variable with $.getJSON(url) it does not seem to parse the array, console simply returns the whole object...
  • user2478342
    user2478342 almost 11 years
    Thanks again- when I enter the url and run the script I am now getting "SyntaxError: JSON Parse error: Unexpected identifier "object" in the error console?
  • SilverRay
    SilverRay about 8 years
    How to refresh the td for new data?
  • sijpkes
    sijpkes almost 8 years
    the OP asked for a table not a dropdown list
  • Manahil
    Manahil about 7 years
    @pmandell I am using the code you provided in the Fiddle. However I only get table header and no data or table.
  • Jasen
    Jasen almost 7 years
    script injection vuln.
  • ttulinsky
    ttulinsky about 4 years
    FYI: html on JSFiddle is <table> <tr> <th>User_Name</th> <th>score</th> <th>team</th> </tr> </table>