Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
47 views
in Technique[技术] by (71.8m points)

javascript - Parsing JSON objects for HTML table

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)

question from:https://stackoverflow.com/questions/17066636/parsing-json-objects-for-html-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...