Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

214
Visualizações
Using Fetch to import JSON data and output to an HTML Table

I'm learning JavaScript and trying to master what should be a basic process, fetching data from a .json file and outputting it to an HTML Table.

No problem when I uncomment the first 7 lines of code and comment out the next 3 lines that use 'fetch' . However when I try to 'fetch' and output the data from another file I get the error that I've indicated at line #39 (let data = Object.keys(mountains[0]. I checked the console.log and the 'names.json' file is there as expected so the problem is not with a file path or with the fetch request. I think my problem is at line 39 with the 'Object.keys function. I'm at a loss as to how to reference the json data that was fetched. Any help appreciated!

/*let mountains = [
    { name: "Monte Falco", height: 1658, place: "Parco Foreste Casentinesi" },
    { name: "Monte Falterona", height: 1654, place: "Parco Foreste Casentinesi" },
    { name: "Poggio Scali", height: 1520, place: "Parco Foreste Casentinesi" },
    { name: "Pratomagno", height: 1592, place: "Parco Foreste Casentinesi" },
    { name: "Monte Amiata", height: 1738, place: "Siena" }
  ]; */
  
 (fetch("names.json")
  .then(res => res.json()
  .then(json => console.log(json))))
  
  
  function generateTableHead(table, data) {
    let thead = table.createHead();
    let row = thead.insertRow();
    for (let key of data) {
      let th = document.createElement("th");
      let text = document.createTextNode(key);
      th.appendChild(text);
      row.appendChild(th);
      
    }
  }
  
  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      for (key in element) {
        let cell = row.insertCell();
        let text = document.createTextNode(element[key]);
        cell.appendChild(text);
      }
    }
  }
  
      
let table = document.querySelector("table");
let data = Object.keys(mountains[0]); //****************************** Uncaught ReferenceError: mountains is not defined
generateTable(table, mountains); // generate the table first
generateTableHead(table, data); // then the head

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can try something like this:

fetch("names.json")
  .then(res => res.json())
  .then(json => {
    console.log(json)
    // you need to get mountains from json
    // if json is in the shape that is needed then leave as it is 
    const mountains = json
    let table = document.querySelector("table");
    let data = Object.keys(mountains[0]);
    generateTable(table, mountains); // generate the table first
    generateTableHead(table, data); // then the head
  })
about 4 years ago · Juan Pablo Isaza Relatório

0

When you comment first 7 lines of code so the mountains variable becomes undefined as it is not created yet. So to run this code you can do your stuff inside the second callback of fetch function i.e. when you get the data in json format, like:

function generateTableHead(table, data) {
  let thead = table.createHead();
  let row = thead.insertRow();
  for (let key of data) {
    let th = document.createElement("th");
    let text = document.createTextNode(key);
    th.appendChild(text);
    row.appendChild(th);
    
  }
}

function generateTable(table, data) {
  for (let element of data) {
    let row = table.insertRow();
    for (key in element) {
      let cell = row.insertCell();
      let text = document.createTextNode(element[key]);
      cell.appendChild(text);
    }
  }
}

fetch("names.json")
.then(res => res.json())
.then(json => {

    let mountains = json;
    let table = document.querySelector("table");
    let data = Object.keys(mountains[0]);
    generateTable(table, mountains); // generate the table first
    generateTableHead(table, data); // then the head

})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda