我正在try 显示一个基于JSON数据的"排行榜"表.

我读了很多关于JSON格式的书,并克服了一些最初的障碍,但我的Javascript知识非常有限,我需要帮助!

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.

下一步是按分数降序对条目进行排序.

任何帮助都将不胜感激.

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);
    }
});

(没有必要使用$.parseJSON,我们可以使用'data',因为我相信JSON数组已经被解析了)

推荐答案

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

Json相关问答推荐

2020-12年草案中的Json列举模式

我可以使用JQ来缩小数组中的json对象的范围吗?

与错误相关的未定义&Quot;不是有效的JSON

通过在织女星简化图上裁剪来显示文本

在Zig中解析JSON失败

使用快速json库编写json可以消除所有缩进

将boost::beast::multibuffer转换为std::istream

jq :遍历 json 并在键存在时检索集合

如何将 JSON 文本作为参数传递给 powershell?

JOLT 获取带有动态键的数组

传统编程语言等价于动态 SQL

如何使用 ConfigurationBuilder 解析现有的 json 字符串(不是文件)

python,将Json写入文件

Python Flask-Restful POST 不采用 JSON 参数

在 Apache Spark 中读取多行 JSON

如何使用 Swift 从 NSURLSession 获取 cookie?

反序列化大型 json 对象的 JsonMaxLength 异常

如何在已声明的 JSON 对象中添加键值对

从 Json 对象 Android 中获取字符串值

如何在 JAVA 中对 JSONArray 进行排序