What is the best way to generate a table using JSON data from a remote source?

I have successfully created a table from JSON data using the example code provided below. However, I am now facing a challenge in connecting to remote URLs that contain JSON content for the purpose of generating tables. I came across this URL that leads to a JSON page which I would like to use to create a table with information such as continent, country, cases, deaths, recovered, and last updated. I aim to achieve a similar table result as the one in the example. If there are any discussions or solutions related to this topic, please share them in the comments without deleting this topic.

TABLE.HTML (JSON data is on a remote page, aiming to create a table from it)

<!DOCTYPE html>
<html>
<head>
    <title>Convert JSON Data to HTML Table</title>
    <style>
        th, td, p, input {
            font:14px Verdana;
        }
        table, th, td 
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>

    <p id="showData"></p>
</body>

<script>

        var myBooks = [
            {
                "Book ID": "1",
                "Book Name": "Computer Architecture",
                "Category": "Computers",
                "Price": "125.60"
            },
            {
                "Book ID": "2",
                "Book Name": "Asp.Net 4 Blue Book",
                "Category": "Programming",
                "Price": "56.00"
            },
            {
                "Book ID": "3",
                "Book Name": "Popular Science",
                "Category": "Science",
                "Price": "210.40"
            }
        ]

        // EXTRACT VALUE FOR HTML HEADER. 
        // ('Book ID', 'Book Name', 'Category' and 'Price')
        var col = [];
        for (var i = 0; i < myBooks.length; i++) {
            for (var key in myBooks[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < myBooks.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myBooks[i][col[j]];
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);

</script>
</html>

Answer №1

Unfortunately, your previous data source is no longer providing data. I have switched it to a source that mirrors daily statistics compiled by the John Hopkins University in Baltimore, MD. Due to the nature of this data being in a time series format, some pre-processing was required before displaying it in the table below. The styling of the table is handled by specific lines of CSS:

const num=s=>+s.replace(/[^0-9]/g,''),
  cols=["country","cases","deaths","recovered","deathrate"];
fetch('https://pomber.github.io/covid19/timeseries.json').then(r=>r.json()).then(o=>{
  var D=Object.keys(o).sort().map(c=>{
    let dat=Object.values(o[c].slice(-1)[0]);
    dat[0]=c;dat.push((100*dat[2]/dat[1]).toFixed(2)+'%');
    return dat
  })
  document.querySelector('table').innerHTML='<tr>'+
  cols.map(s=>
    `<th>${s}</th>`).join('')+'</tr><tr>'
     +D.map(r=>`<td>${r.join('</td><td>')}</td>`)
       .join('</tr><tr>')+'</tr>';
 })
th:first-child {text-align:left}
th:nth-child(n+2), td:nth-child(n+2) {text-align:right}
th:nth-child(2) {background-color: #00aa22}
th:nth-child(3) {background-color: #ffff00}
th:nth-child(4) {background-color: #ff0000}
th:nth-child(5) {background-color: #ff9900}
td:nth-child(2) {background-color: #55ee77}
td:nth-child(3) {background-color: #ffff55}
td:nth-child(4) {background-color: #ff0000}
td:nth-child(5) {background-color: #ffb84d}
<table></table>

For additional functionality, I have implemented sorting options in the table. Simply click on any column header to sort the table based on that column (click again for reverse order):

const num=s=>+s.replace(/[^0-9]/g,''),
  cols=["country","cases","deaths","recovered","deathrate"];
const tblsort=ev=>{const e=ev.target; if (e.tagName=='TH'){
   const i=[...e.parentNode.children].indexOf(e); srtdir[i]=srtdir[i]>0?-1:1;
   [...tbd.children].sort(i>0?srtnum(i):srttxt(i)).forEach(tr=>tbd.appendChild(tr));
  }
};
const srtdir=[];
const srtnum=i=>(a,b)=>srtdir[i]*num(a.children[i].textContent)-num(b.children[i].textContent);
const srttxt=i=>(a,b)=>srtdir[i]*a.children[i].textContent.localeCompare(b.children[i].textContent);
fetch('https://pomber.github.io/covid19/timeseries.json').then(r=>r.json()).then(o=>{
  var D=Object.keys(o).sort().map(c=>{
    let dat=Object.values(o[c].slice(-1)[0]);
    dat[0]=c;dat.push((100*dat[2]/dat[1]).toFixed(2)+'%');
    return dat
  })
  document.querySelector('table').innerHTML='<thead><tr>'+
  cols.map(s=>
    `<th>${s}</th>`).join('')+'</tr></thead><tbody><tr>'
     +D.map(r=>`<td>${r.join('</td><td>')}</td>`)
       .join('</tr><tr>')+'</tr></tbody>';
  tbd=document.querySelector('tbody');
  thd=document.querySelector('thead').addEventListener('click',tblsort);
 })
th {cursor:pointer}
th:first-child {text-align:left}
th:nth-child(n+2), td:nth-child(n+2) {text-align:right}
th:nth-child(2) {background-color: #00aa22}
th:nth-child(3) {background-color: #ffff00}
th:nth-child(4) {background-color: #ff0000}
th:nth-child(5) {background-color: #ff9900}
td:nth-child(2) {background-color: #55ee77}
td:nth-child(3) {background-color: #ffff55}
td:nth-child(4) {background-color: #ff0000}
td:nth-child(5) {background-color: #ffb84d}
<table></table>

Answer №2

To begin, you can start by using either XMLHttpRequest or Fetch to fetch the data from a remote source. After obtaining the data, you can then parse it using JSON.parse. Once you have successfully parsed the data, you can proceed to create your table based on the sample code provided.

If you are not familiar with using pure JavaScript, there are various libraries available for both XMLHttpRequest and Fetch that you can utilize.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to switch around div elements using CSS

There are two unordered list items in a container div and one swap button. When the swap button is clicked, the order of items needs to change. This functionality can be achieved using the following swap function. var ints = [ "1", "2", "3", "4" ], ...

utilize images stored locally instead of fetching them from a URL path in a Vue.js project

Hey there fellow Developers who are working on Vuejs! I'm encountering something strange in the app I'm building. I am attempting to modify the path of image requests based on a particular result, which causes the images to change according to th ...

Adding custom script tags to a React application

I'm interested in integrating a StreamingVideoProvider video player into my React application but facing some challenges: I do not have direct access to the video URL I want to utilize their JS video player for its advanced features like password pro ...

What is the best way to call the app.js function from an HTML page in an Express.js environment

Is there a way to trigger the function init() { // } located in app.js from an HTML page? <a href='javascript:init();'> Trigger init </a> The issue with the code above is that it searches for function init() only on the client side ...

"Can someone provide guidance on extracting the ID from a JSON value and storing it in a

Hey there, I have come across this jQuery code snippet: var fbuid = zuck; var fbjson = $.getJSON("https://graph.facebook.com/"+fbuid); I am wondering how to extract the id directly from the JSON response into a variable : { id: "4", first_name: "Mark", ...

Grid of pictures resembling a masonry pattern

As I ponder this intricate dilemma, I am convinced that there must be a simple solution or alternative approach to finding the answer. My goal is to create a grid of random images without any gaps between them. I have an array of images that I want to dis ...

Guide to linking an external URL with a lightbox image

I have created a gallery and an admin gallery page. In the admin gallery, there is a delete button that appears over the image. However, when I click on it, instead of showing the message "Are you sure?", it opens a lightbox. I suspect that the code for t ...

Guide on accessing APIs for individual elements in an array

Currently utilizing Next.js / React.js and making use of this API to retrieve information about a specific country. Within the response, there exists an array called borders, as shown below: borders: [ "CAN", "MEX", ], There is ...

Issues with jQuery fundamentals

For a while now, I've been grappling with jQuery. It's undeniably powerful and offers a plethora of fantastic capabilities. However, my struggle lies in the fact that I tend to incorporate multiple jQuery features simultaneously. For example, on ...

VueJS emits a warning when filtering an array inside a for loop

I'm encountering an issue with my filtering function in VueJS. While it works fine, I am seeing a warning message in the console. You can check out this example to see the problem. The problem arises when I need to filter relational data from a separ ...

Retrieving Json value based on a different value in Python

folders_list = { "folders": [{ "id": "866699", "name": "Folder1", "files_count": 0, "size": "0", "has_sub": false }, { "id": "866697", "name": "Folder2", "files_count": 0, "size": "0", "has_sub": false }] I a ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

Make a quick call to the next function within the error handling module for a

Currently, I am facing an issue while trying to call the next function within the error handler of my node + express js application. In each controller, I have a middleware known as render which is invoked by calling next, and I wish to achieve the same f ...

issue encountered when trying to deploy a React application on GitHub

I successfully created a todolist on localhost. Now, I am facing issues while deploying it on GitHub. When I run '$ npm run deploy' in the command prompt, I encounter errors. To troubleshoot, I have added 'homepage', 'predeploy&ap ...

Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. ...

Converting multi-dimensional arrays to JSON format

My current challenge involves printing and encoding my data into JSON format. Specifically, I am extracting data from my MySQL database to create a quiz. Each quiz set consists of 1 question, 1 category, and 4 options. I believe I am close to figuring out ...

Encountering a 404 error on Vercel deployment of NextJS

I am currently utilizing a custom express server in conjunction with NextJS. During local development, everything runs smoothly. However, upon deployment to Vercel, I encounter 404 errors when attempting to access my backend API. What could be causing th ...

How can one access the content of posts on a Facebook profile directly from the HTML source code?

Recently, I developed a web scraper using Python, Selenium, and BS to navigate through various websites based on a list of URLs. The output is the raw HTML source code saved in a CSV file for further processing which involves cleaning and extracting keywor ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...

What is the reason for JWT tokens using Base64 encoding instead of UTF-8?

RFC 7515 Section 3 states: Both the JWS Protected Header, JWS Payload, and JWS Signature are base64url encoded in both serializations because JSON does not have a direct way of representing arbitrary octet sequences. What is the limitation that prevents ...