首页 > 解决方案 > 在 html 表中显示一个 json 数组

问题描述

我正在尝试在 HTML 中显示一个 JSON 数组,我得到的响应是

[
  {
    "New  upto 3 Yrs": 40.0,
    "Above 3 yr to 9 yrs": 35.0,
    "Above 9 yrs upto 12 yrs": 30.0
  }
]

在这里,我得到了未定义的价值。(见快照 输出图像)如何在 HTML 中将这种 JSON 显示为 html 表?

这是我的脚本:

 success: function (data) {
            if (objMotorUnderwritingList.ddlVehicleType == "TW$") {
               // alert("hi TW$");
                if (data.jsDiscoundGridList != 0) {

                        var eachrow = "<tr>"
                                    + "<td>" + data.jsDiscoundGridList[0]["New upto 3 Yrs"] + "</td>"
                                    + "<td>" + data.jsDiscoundGridList[0]["Above 3 yr to 9 yrs"] + "</td>"
                                    + "<td>" + data.jsDiscoundGridList[0]["Above 9 yrs upto 12 yrs"] + "</td>"
                                    + "</tr>";
                        $('.tbody').html(eachrow);

                    }
                else {
                    ShowAlert("Something Wrong in TW");
                } 
            }}

标签: javascripthtml

解决方案


您的属性名称中有额外的空格,如果您更改它,您可以很好地访问属性:

你的代码:

let data = {
  jsDiscoundGridList: [{
    "New  upto 3 Yrs": 40.0,
    "Above 3 yr to 9 yrs": 35.0,
    "Above 9 yrs upto 12 yrs": 30.0
  }]
};

console.log(data.jsDiscoundGridList[0]["New upto 3 Yrs"]); // undefined
//                                         ^

使用正确的间距:

let data = {
  jsDiscoundGridList: [{
    "New  upto 3 Yrs": 40.0,
    "Above 3 yr to 9 yrs": 35.0,
    "Above 9 yrs upto 12 yrs": 30.0
  }]
};

console.log(data.jsDiscoundGridList[0]["New  upto 3 Yrs"]); // 40
//                                         ^^


推荐阅读