Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda