如何进行json数组迭代?

时间:2016-05-30 18:30:13

标签: javascript html json

我的json数组就像在html页面中收到的那样如何在表格中显示?意味着迭代.plz帮助?我是新人。

[
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"},
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"},
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"}
] 

2 个答案:

答案 0 :(得分:0)

迭代数组并将其显示在表格中:

var jsonObject = [
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"},
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"},
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"}
];

var output = "<table>";
for (var i = 0, len = jsonObject.length; i < len; i++) {
    var line = jsonObject[i];
    output += "<tr>";
    output += "<td>" + line.studentId + "</td>";
    output += "<td>" + line.firstName + "</td>";
    output += "<td>" + line.lastName + "</td>";
    output += "<td>" + line.year + "</td>";
    output += "<td>" + line.course + "</td>";
    output += "</tr>";
}
output += "</table>";

document.getElementById(...).innerHTML = output;

答案 1 :(得分:0)

首先,JSON是(JavaScript Object Notation)。相同的JS,只是用于对象表示法的略有不同的语法。

您需要使用AJAX才能从其他文件接收JSON数据,只需查看:

var xhr = new XMLHttpRequest();
var url = "myJSON.json"; // your JSON text file

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var myResponse = JSON.parse(xhr.responseText);

        display(myResponse); // send array to function
    }
}

xhr.open("GET", url, true);
xhr.send(null);

function display(arr) {
    var myTable = "<table>"; // create a table variable

    for (var i = 0; i < arr.length; i++) { // loop through array
        myTable += "<tr>";
        myTable += "<td>" + arr[i].studentId + "</td>";
        myTable += "<td>" + arr[i].firstName + "</td>";
        myTable += "<td>" + arr[i].lastName + "</td>";
        myTable += "<td>" + arr[i].year + "</td>";
        myTable += "<td>" + arr[i].course + "</td>";
        myTable += "</tr>";
    }

    myTable += "</table>";

    document.getElementById("myAwesomeTable").innerHTML = myTable; // display the final result in to html
}
  1. 使用AJAX打开您的JSON文本文件,它可能是.txt,.json等。
  2. 使用JSON.parse()将JSON文本转换为数组
  3. 发送该数组以实现
  4. 创建一个表并将所有内容保存在变量中,如文本
  5. 循环数组
  6. 将您的表格显示为html