首页 > 解决方案 > 我该如何循环这个 JSON 数据

问题描述

我有想要显示为 HTML 表格的 JSON 数据:

{
  "foo": {
    "col-1": "foo",
    "col-2": "faa",
    "col-3": "foobar"
  },
  "faa": {
    "col-1": "foo",
    "col-2": "faa",
    "col-3": "foobar"
  }
}

到目前为止,我尝试简单地res.length使用循环进行迭代while,但res.length返回为undefined以及 usingJSON.parsefor ... in循环。都没有奏效。

到目前为止我的代码:

const startingNode = document.querySelector("#appendTable");

const table = document.createElement("table");
const tbody = document.createElement("tbody");

const req = new XMLHttpRequest();
const reqURL = "http://localhost:8000/dict_en.json";

req.open("GET", reqURL);
req.responseType = "json";
req.send();
req.onload = () => {
  const res = JSON.parse(req.response);
  console.log(res.length);
  let i = 0;
  while (i < res.length) {
    console.log(i);
    i++;
  }
}

table.innerHTML = "<thead><tr><td>Foo<td>Faa</td><td>Foobar</td></td></tr></thead>";

table.appendChild(tbody);
startingNode.appendChild(table);

标签: javascriptjson

解决方案


推荐阅读