如何使用JavaScript将嵌套的JSON文件项导出到HTML表?

时间:2019-03-10 23:41:22

标签: javascript json

我正在尝试将JSON文件数据导出到表中,但是我不确定如何访问JSON文件的嵌套元素。

这是我的JSON:

{
"fruits color": "red",
"farmers market": "2019",
"sellers": [{
    "day": "1",
    "seller": [{
            "name": "John",
            "sales": "50",
            "types": "3",
            "type": [
                "apples",
                "strawberries",
                "rapsberries"
            ]
        },
        {
            "name": "Adam",
            "sales": "45",
            "types": "2",
            "type": [
                "cranberries",
                "redcurrants"
            ]
        }
    ]
}   
]}

我有一个简单的HTML表单,可以从下拉菜单中选择文件。

选择文件后,我的JavaScript函数会从文件中提取信息并将其发送到表中:

function fruitSelection() {
var items = document.getElementById("fruit-colors");
var value = items.options[items.selectedIndex].value;
    if (value == "red") {
        JSON = "redfruits.json"
        processFruitsFile()}}

function processFruitsFile() {
  $.getJSON(JSON, function(JSONdata) {
    var JSONItems= [];

$.each(JSONdata, function(key, value) {
        JSONItems.push( "<tr" + key + "'>" + value + "</tr>");
});
    $( "<tr/>", {
        "class": "result-items",
        html: JSONItems.join("")
}).appendTo(result);});}

现在我遇到的问题是我的函数只能与第一个键和值对一起使用,如下所示:  red2019[object Object]

我要实现的是一张表,其中可以显示类似以下内容的内容:

Day Seller Type 1   Type 2        Type 3
1   John   apples   strawberries  raspberries

我该如何访问嵌套在“卖方”和“水果类型”中的那些值并对其进行格式化?

感谢帮助!

1 个答案:

答案 0 :(得分:1)

这是使用Javascript的方法

let obj = {
"fruits color": "red",
"farmers market": "2019",
"sellers": [{
    "day": "1",
    "seller": [{
            "name": "John",
            "sales": "50",
            "types": "3",
            "types of fruits": [
                "apples",
                "strawberries",
                "rapsberries"
            ]
        },
        {
            "name": "Adam",
            "sales": "45",
            "types": "2",
            "types of fruits": [
                "cranberries",
                "redcurrants"
            ]
        }
    ]
}   
]}
function createTable(obj){
  let table = document.createElement('table'); 
  table.className = 'table';
  let thead = document.createElement('thead');
  let tbody = document.createElement('tbody');
  let noOfFriuts = 0;
  let {sellers}  = obj 
  for(let day of sellers){ 
    for(let seller of day.seller){
      let tr = document.createElement('tr');
      tr.innerHTML += `<td>${day.day}</td>`
      tr.innerHTML += `<td>${seller.name}</td>`
      for(let fruit of seller['types of fruits']){ 
        
        tr.innerHTML += `<td>${fruit}</td>`
      }
      noOfFriuts  = Math.max(noOfFriuts ,seller['types of fruits'].length);
      tbody.appendChild(tr)
    }
    
  }
  let tr = document.createElement('tr');
  tr.innerHTML = `<th>Day</th>
    <th>Name</th>`  
  for(let i = 1;i<=noOfFriuts;i++){
    let th = document.createElement('th');
    th.innerHTML = `Type ${i}`
    tr.appendChild(th)
  }
  
  thead.appendChild(tr);
  table.appendChild(thead);
  table.appendChild(tbody);
  document.body.appendChild(table);
  document.querySelectorAll('tr').forEach(tr => {
    let dif = -(tr.cells.length - noOfFriuts - 2);
    for(let i = 0;i<dif;i++) tr.innerHTML += "<td></td>"
  })
  
}
console.log('x')
createTable(obj);
table{
  padding:2px;
  border-collapse:collapse;
  border:2px solid;
}
td,th{
border:1px solid;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>