skip to Main Content

I’m currently trying to display JSON data as a table
in a web page: the raw data from the API url looks like this:

{"body":"[{"id":"67341472528","name":"Dana Fin"},{"id":"87543263550","name":"Jon Doe"}]"}

I was trying to use the jQuery/AJAX $.getJSON() Method and it displays the data like this:

[{"id":"67341472528","name":"Dana Fin"},{"id":"87543263550","name":"Jon Doe"}]

but then I’ve been trying to put that data into a table for a while, I’ve tried a lot of things and examples but nothing has worked.

so basically I was wondering if somebody has done something like this, thanks

2

Answers


  1. Try something like this:

    // response from $.getJson()
    const data = [{
      "id": "67341472528",
      "name": "Dana Fin"
    }, {
      "id": "87543263550",
      "name": "Jon Doe"
    }]
    
    const table = document.createElement('table')
    table.border = 1
    
    // create header row for table)
    const header = document.createElement('tr')
    const idHeader = document.createElement('th')
    idHeader.appendChild(document.createTextNode('id'))
    const nameHeader = document.createElement('th')
    nameHeader.appendChild(document.createTextNode('name'))
    header.appendChild(idHeader)
    header.appendChild(nameHeader)
    table.appendChild(header)
    
    // create entries for each response
    for (const entry of data) {
      const row = document.createElement('tr')
      const id = document.createElement('td')
      id.appendChild(document.createTextNode(entry.id))
      const name = document.createElement('td')
      name.appendChild(document.createTextNode(entry.name))
      row.appendChild(id)
      row.appendChild(name)
      table.appendChild(row)
    }
    
    document.querySelector('body').appendChild(table)

    Here is a working CodePen

    Login or Signup to reply.
  2. Using a slightly terser syntax:

    // response from $.getJson()
    const data = [{
      "id": "67341472528",
      "name": "Dana Fin"
    }, {
      "id": "87543263550",
      "name": "Jon Doe"
    }];
    
    const header = `
      <tr>
        <th>ID</th>
        <th>NAME</th>
      </tr>
    `
    
    document.querySelector("#data").innerHTML = data.reduce(( innerHTML, { id, name }) => (
      
      `
        ${ innerHTML }
        <tr>
          <td>${ id }</td>
          <td>${ name }</td>
        </tr>
      `
      
    ), header );
    table, tr, td {
      border-collapse: collapse;
      border: 1px solid;
      padding: 5px;
    }
    <table id="data"></table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search