JavaScript 从复杂的 JSON 中获取数据

javascript fetch data from complex JSON

本文关键字:获取 数据 JSON 复杂 JavaScript      更新时间:2023-09-26

有一个json(#json),如下所示,在学生部分,前两个是一个组,后两个是一个组。按一组编号分组。像1号和2号是一组)。
问题是我需要从学生部分获取数据并制作 2 个表(取决于本例中有多少组 no.2)。如何以编程方式修改 json 数据结构,以便我可以获取数据来执行上述操作?

表(#table1)如下所示:
不。名字
1 汤姆
2 杰基

编号名称
1 汤姆
2 杰基



#json

{
"people": {
    "student": [{
        "name": "tom"
        "no.": "1"
        "other": "a"
    },{
        "name": "tom"
        "no.": "1"
        "other": "e"
    },{
        "name": "jack"
        "no.": "2"
        "other": "d"
    },{
        "name": "tom"
        "no.": "1"
        "other": "c"
    },{
        "name": "tom"
        "no.": "1"
        "other": "d"
    },{
        "name": "jack"
        "no.": "2"
        "other": "g"
    }]      
}}

这是我的 jsRender 模板:

    <table>      
    <thead>
        <tr><td>Table 1</td></tr> 
        <tr><td>no.</td><td>name</td></tr> 
    </thead> 
    <tbody>
    {{for student}}
        <td>{{>no.}}</td>
        <td>{{>name}}</td>
    {{/for}}
    </tbody>
</table>

它将输出:

no. name
1 tom
2 jacky
1 tom
2 jacky

如何修改模板以使输出像 #table1

你需要这样的东西:

var yourJSON; // All JSON data
var studentData = yourJSON.people.student; // Student array
var tableIndex = 1; // Index for table name
// Loop to print student data
for (var i = 0, length = studentData.length; i < length; i++) {
    if (studentData[i]['no.'] == '1') {
        if (tableIndex > 1) {
            print('</tbody></table>');
        }
        print('<table>' +
            '<thead>' +
                '<tr>' +
                    '<td>Table ' + tableIndex + '</td>' +
                '</tr>' + 
                '<tr>' +
                    '<td>no.</td>' +
                    '<td>name</td>' +
                '</tr>' + 
            '</thead>' +
            '<tbody>');
        tableIndex++;
    }
    print('<tr><td>' + studentData[i]['no.'] + '</td>');
    print('<td>' + studentData[i]['name'] + '</td></tr>');
}
print('</tbody></table>'); // Closing the last table

我不知道您的模板引擎是如何工作的,所以我使用打印功能来显示需要在模板中添加的内容。