简体   繁体   中英

Parsing JSON with JavaScript to HTML

I have an html table:

<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>

If I had a JSON file with two more data sets, how can I parse them in Javascript so each new object creates a new tr?

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

I would need my new HTML to look like this:

 <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>

etc.

I've only parsed in Ruby before, and I had to 'require = json'' on the top of the file. Do I still have to do that?

Thanks!

You could use jQuery to read the JSON file and parse the results

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

Let me know if you need help iterating over the data and I will edit to provide more.

It's a little late but this javascript will do what you ask. One important note is that it collects the columns from the first object in the array. Therefor if other objects follow later on that have more columns, they will not be included in your list.

 //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); }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM