将嵌套的JSON数据转换为表 [英] Converting nested JSON data into a table

查看:56
本文介绍了将嵌套的JSON数据转换为表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将嵌套的JSON数据转换为HTML表,但是它始终抛出错误.

I'm trying to convert the nested JSON data into a HTML table, but it kept throwing error.

我不确定我做错了什么.访问对象内部数组的方法可能有问题吗?

I am not sure where I did wrong. Maybe something's wrong with the method of accessing the array inside the object?

它一直抛出此错误:

无法将属性'innerHTML'设置为null"

"Cannot set property 'innerHTML' of null"

下面是我写的代码:

function DonutTable(array){
    //create a table element
    var table = document.createElement("table");
    //create header columns

    var col = Object.keys(array[0]); //array of keys
    //write keys onto the header cell
    var tr = table.insertRow(-1);
    col.forEach(function(key){
        var th = document.createElement("th");
        th.textContent = key;
        tr.appendChild(th);
    });

    //create rows to hold the rest of the data
    array.forEach(function(obj){
        //for each obj in the main array, create a row
        var data_row = table.insertRow(-1);
        //for each header in the col array, populate data
        col.forEach(function(key){
            var tabCell = data_row.insertCell(-1);
            if (key==="batters"){
                //grab the value of batters and access value of batter
                obj["batters"]["batter"].forEach(function(e){
                    //for each e in batter, create a div element
                    var div = document.createElement("div");
                    //write on the div 
                    div.textContent =  e.type + "(" + e.id + ")";
                    tabCell.appendChild(div); })
                }
            if (Array.isArray(obj[key])){ //check if a value of a key is an array
                obj[key].forEach(function(topping){
                    //for each obj in topping, get id and type 
                    var div = document.createElement("div");
                    div.textContent =  topping.type + "(" + topping.id + ")";
                    tabCell.appendChild(div);
                })
            }
            else{
                tabCell.textContent = obj[key];
            }


                })
            })


    var divContainer = document.getElementById("showTable");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);

}

var donut = [
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": 
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]
DonutTable(donut);

<html>
    <head>
        <title>HTML Donut Table from JSON</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <input type="button" value="Generate a table" onclick="DonutTable()">
        <div id="showTable"></div>
    </body>
</html>

推荐答案

这是您的确切代码,我只是将其分为JS和HTML部分.

This is your exact code that I just split into JS and HTML parts.

由于donut数组已显式传递给DonutTable()函数,因此它在初始运行时有效.由于您的HTML调用DonutTable()不带参数,因此按钮单击不起作用.

It works on initial run since donut array is explicitly passed to DonutTable() function. It does not work on button click since your HTML calls DonutTable()with no parameters.

function DonutTable(array){
    //create a table element
    var table = document.createElement("table");
    //create header columns

    var col = Object.keys(array[0]); //array of keys
    //write keys onto the header cell
    var tr = table.insertRow(-1);
    col.forEach(function(key){
        var th = document.createElement("th");
        th.textContent = key;
        tr.appendChild(th);
    });

    //create rows to hold the rest of the data
    array.forEach(function(obj){
        //for each obj in the main array, create a row
        var data_row = table.insertRow(-1);
        //for each header in the col array, populate data
        col.forEach(function(key){
            var tabCell = data_row.insertCell(-1);
            if (key==="batters"){
                //grab the value of batters and access value of batter
                obj["batters"]["batter"].forEach(function(e){
                    //for each e in batter, create a div element
                    var div = document.createElement("div");
                    //write on the div 
                    div.textContent =  e["type"] + "(" + e["id"] + ")";
                    tabCell.appendChild(div); })
                }
            else if (Array.isArray(obj[key])){ //check if a value of a key is an array
                obj[key].forEach(function(topping){
                    //for each obj in topping, get id and type 
                    var div = document.createElement("div");
                    div.textContent =  topping.type + "(" + topping.id + ")";
                    tabCell.appendChild(div);
                })
            }
            else{
                tabCell.textContent = obj[key];
            }


                })
            })


    var divContainer = document.getElementById("showTable");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);

}

var donut = [
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": 
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]
DonutTable(donut);

<html>
    <head>
        <title>HTML Donut Table from JSON</title>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <input type="button" value="Generate a table" onclick="DonutTable()">
        <div id="showTable"></div>
    </body>
</html>

这篇关于将嵌套的JSON数据转换为表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆