簡體   English   中英

使用JavaScript將JSON解析為HTML

[英]Parsing JSON with JavaScript to HTML

我有一個html表:

<table class='headers'>
  <tr>
    <th>Gender</th>
    <th>Height</th> 
    <th>Weight</th>
    <th>Age</th>
    <th>Occupation</th>
  </tr>
   <tr>
     <td>Male</td>
     <td>5'11</td> 
     <td>160</td>
     <td>35</td>
     <td>Doctor</td>
    </tr>
  </table>

如果我有一個包含兩個以上數據集的JSON文件,該如何在Javascript中解析它們,以便每個新對象都創建一個新的tr?

jsonData = [
  {
    "Gender": "Female",
    "Height": 5'2,
    "Weight": 100,
    "Age": 25,
    "Occupation": "Lawyer"
  },
  {
    "Gender": "Male",
    "Height": 5'9,
    "Weight": 150,
    "Age": 23,
    "Occupation": "Student"
  }
 ]

我需要新的HTML看起來像這樣:

 <table class='headers'>
  <tr>
    <th>Gender</th>
    <th>Height</th> 
    <th>Weight</th>
    <th>Age</th>
    <th>Occupation</th>
  </tr>
   <tr>
     <td>Male</td>
     <td>5'11</td> 
     <td>160</td>
     <td>35</td>
     <td>Doctor</td>
    </tr>
  </table>
   <tr>
     <td>Female</td>
     <td>5'2</td> 
     <td>100</td>
     <td>25</td>
     <td>Lawyer</td>
    </tr>
  </table>

等等

我以前僅在Ruby中進行過解析,而我必須在文件頂部使用“ require = json”。 我還需要這樣做嗎?

謝謝!

您可以使用jQuery讀取JSON文件並解析結果

$.getJSON('file.json', function (response) {
    // this is where you would iterate over the json and create the element
});

讓我知道您是否需要遍歷數據的幫助,我將進行編輯以提供更多信息。

有點晚了,但是這個javascript可以滿足您的要求。 一個重要的注意事項是它從數組中的第一個對象收集列。 因此,如果后面跟隨的其他對象具有更多的列,則它們不會包含在列表中。

 //build table from ARRAY of jsonObjects function dataToTable(gotData){ var tableDiv = document.createElement('div'); tableDiv.id = 'TABLE'; var table = document.createElement('table') var tableBody = document.createElement('tbody'); //build columHeaders var hrow = document.createElement('tr'); for(col in gotData[0]){ console.log(col, gotData[0][col]); var hcell = document.createElement('td'); hcell.innerHTML = '<b>' + col + '</b>'; hrow.appendChild(hcell); } tableBody.appendChild(hrow); //build dataRows for(row in gotData){ var drow = document.createElement('tr'); for(col in gotData[row]){ var dcell = document.createElement('td'); dcell.innerHTML = gotData[row][col]; drow.appendChild(dcell); } tableBody.appendChild(drow); } table.appendChild(tableBody); tableDiv.appendChild(table); document.body.appendChild(tableDiv); }; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM