Home > Blockchain >  JSON File to HTML Table Using Fetch
JSON File to HTML Table Using Fetch

Time:04-12

I would like to have an HTML data fetch data from a JSON file. I am using fetch, but I am just getting a blank table. I looked in Console and do not see any CORS errors. What is preventing it from displaying the data?

Script

<script>
fetch ("https://gsx2json.com/api?id=1Jvqj6ArHXr0lqW7LR4P2Y0M4i0egcGX-3Ah4PFp4rvA&sheet=Sheet1").then((data)=>{
  return data.json();
}).then((objectData)=>{
  console.log(objectData[0].title);
  let tableData="";
  objectData.map((values=>{
      tableData ='<tr>
        <td>${values.Bill}</td>
        <td>${values.Action}</td>
        </tr>';
  
  });
  document.getElementById("table_body").
  innerHTML=tableData;
})

</script>

Table (HTML)

  <table >
<thead>
  <tr>
    <th>Bill</th>
    <th>Action</th>
  </tr>
</thead>
<tbody id="table_body">

</tbody>

CodePudding user response:

Okay, I understood what you are trying to do but your code seems to be a little bit messy. It could be a good suggestion to work with your javascript in another file. I used your way to show you how this could work.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <table >
        <thead>
            <tr>
                <th>Bill</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="table_body">

        </tbody>

        <script>
            fetch("https://gsx2json.com/api?id=1Jvqj6ArHXr0lqW7LR4P2Y0M4i0egcGX-3Ah4PFp4rvA&sheet=Sheet1")
                .then(response => response.json())
                .then(({rows}) => {

                    console.log(rows);
                    let tableData = "";
                    rows.forEach((values => {
                        tableData  = `
                        <tr>
                            <td> ${values.Bill}</td >
                            <td>${values.Action}</td>
                        </tr > `;

                    }))
                    document.getElementById("table_body").
                        innerHTML = tableData;
                })
                .catch(console.error)

        </script>
</body>

</html>

There are some mistakes.

  1. You are receiving an object that contains rows and columns. That means that the objectData has atributes this way:
objectData : {
    columns: [],
    rows: []
}

You were trying to access to objectData as an array when the array is row or columns. So you could use objectData.rows[index] or destructure as I did.

  1. I used foreach statement because map changes the array itself.
  • Related