DEV Community

Tech Master
Tech Master

Posted on

Dynamic html table from Json response.

Hello,
I am a newbie a want to make a simple static corona tracker website but the problem is that the data which i want to use is in json format.
So my question is how can i generate a dynamic html table from json response i get from the API?

  • For Reference, link of json data is
    https://covid-rest.herokuapp.com/pakistan

  • The api response is of the following type:
    {"code":200,"message":"OK","data":{"country_name":"pakistan","total_cases":"2291","new_cases":"173","total_death":"31","new_death":"4","total_recovered":"107","active_cases":"2153","critical_cases":"12","tot_cases_per_million":"10","tot_death_per_million":"0.1"}}

Top comments (10)

Collapse
 
jamesrweb profile image
James Robb • Edited

Assuming the response always looks like that then you could do something like:

function translateResponseKey(key) {
  const translations = [{
    key: 'country_name',
    value: 'Country'
  }, {
    key: 'total_cases',
    value: 'Total cases'
  }, {
    key: 'new_cases',
    value: 'New Cases'
  }, {
    key: 'total_death',
    value: 'Total Deaths'
  }, {
    key: 'new_death',
    value: 'New Deaths'
  }, {
    key: 'total_recovered',
    value: 'Total Recovered'
  }, {
    key: 'active_cases',
    value: 'Active Cases'
  }, {
    key: 'critical_cases',
    value: 'Critical Cases'
  }, {
    key: 'tot_cases_per_million',
    value: 'Cases per million people'
  }, {
    key: 'tot_death_per_million',
    value: 'Deaths per million people'
  }];

  return translations.find(item => item.key === key).value;
}

function renderDataTable(data, selector = "body") {
  const outputContainer = document.querySelector(selector);

  if(!outputContainer) throw new Error("The provided selector does not exist on the page.");


  const table = document.createElement("table");
  const headerRow = document.createElement("tr");
  const dataRow = document.createElement("tr");

  for(let key in data) {
    const headerCell = document.createElement("th");
    const dataCell = document.createElement("td");
    const value = data[key];

    headerCell.textContent = translateResponseKey(key);
    dataCell.textContent = value;

    headerRow.appendChild(headerCell);
    dataRow.appendChild(dataCell);
  }

  table.appendChild(headerRow);
  table.appendChild(dataRow);
  outputContainer.appendChild(table);
}

async function get(url, config = {}) {
  const response = await fetch(url, config);
  const data = await response.text();
  console.log({data});
  return data;
  // return JSON.parse('{"data":{"country_name":"pakistan","total_cases":"2386","new_cases":"268","total_death":"32","new_death":"5","total_recovered":"107","active_cases":"2247","critical_cases":"12","tot_cases_per_million":"11","tot_death_per_million":"0.1"}}');
}

async function main(url) {
 const { data } = await get(url);
 renderDataTable(data);
}

const url = "https://covid-rest.herokuapp.com/pakistan";
// const url = "https://jsonplaceholder.typicode.com/photos";
main(url);

Something like that, there may be some mistakes since I typed this on my phone real quick for you but if you need support I can check later on my computer when I get home or something.

Update:

The code was fine when I wrote it earlier BUT the API endpoint you are trying to access doesn't have a Access-Control-Allow-Origin header set on it and so you cannot request it via the browser using fetch or XMLHttpRequest. If you check the console when you run this code it will tell you that it failed to fetch for this exact reason.

To show an example of a working request I added a commented out line just above the final line of the code snippet, if you comment out the first url constant and uncomment the other one and check the console it will show you data as expected.

To see the expected output without making a request you can use the code as it is just now but in the get function, you can comment out all the code and uncomment the last line of that function body to see how it would look if it were to return properly.

Until that endpoint has the Access-Control-Allow-Origin header set though, you won't be able to access the data like this unless you do it server side for example with a reverse proxy.

Hopefully that all makes sense and if you have comments or questions don't hesitate to ask!

Collapse
 
aliglelo profile image
Tech Master • Edited

Thanks a lot james...
I will check it and update the status..

thanks once again.

UPDATE:
The above code doesn't seems to work with any method bro.

Collapse
 
jamesrweb profile image
James Robb • Edited

I just tested all the cases I told you to try and that I already tested before my final update yesterday and the code works 100% fine..

Thread Thread
 
aliglelo profile image
Tech Master

I checked in the morning but didn't work.
let me check again

Thread Thread
 
jamesrweb profile image
James Robb • Edited

Did you even read my full comment and understand it or did you just copy paste as I expect you did...?

Thread Thread
 
aliglelo profile image
Tech Master • Edited

Read it twice..
Copy pasted it but couldn't understand the reverse-proxy.
Could you please more elaborate it or tell me in some simple way as i am completely newbie and just want a working resource light Covid-19 Tracker.

Thread Thread
 
jamesrweb profile image
James Robb

CovidAPI: covid-api.com/
Reverse proxy: en.wikipedia.org/wiki/Reverse_proxy
CORS: en.wikipedia.org/wiki/Cross-origin...

Read these and come back once you understand reverse proxy and cors or just have questions.

I also recommend the covid api I sent you and not the one you've been using currently, happy to discuss that also.

Try yourself first.. :)

Thread Thread
 
aliglelo profile image
Tech Master • Edited

Thanks a lot once again.


UPDATE:
- Finally found a way by using your provided API and some code.
- And and and learnt about CORS.
Thanks for this all help and guidance.

Thread Thread
 
tanghoong profile image
tanghoong

Hi @TechMaster
Found your post from front page.
Hopefully you did create it, possible can see your final works.

@JamesRobb Thanks for the awesome script you wrote.

Thread Thread
 
jamesrweb profile image
James Robb

You’re welcome 😊