How to convert a JSON file to a table with dynamic columns in HTML

1

What happens is that I want to read a JSON file and that as soon as I read it, I created a table from the file with its respective fields. As for example:

{
"nombre":"Ana",
"edad":20,
"Hobbie":"Cantar" }

And the table is created: Name Age Hobbie Ana 20 Sing

    
asked by Aza Jero 10.03.2018 в 17:53
source

3 answers

1

I commented the following would be ideal first to show an advance on how you are building.

However I show you an example that I just did where I occupy

1.- VueJS (To dump or accommodate the data in a simpler way within a table in my HTML )
2.- Axios (for handling requests AJAX ) 3.- In order for VueJS to work it needs to be within the context of a HTML tag with an id, which for example I put app 4.- With the v-for directive, I get the same result as if I were using a foreach loop but in a cleaner way at the code level 5.- I declare an empty arrangement called data that after the request by means of Axios will be filled dynamically 6.- the method mounted is used to indicate that the code of the instance of Vue works once this instance is created and ready

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <table>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Sex</th>
            </tr>
            <tr v-for="dato in datos">
                <td>{{ dato.name }}</td>
                <td>{{ dato.age }}</td>
                <td>{{ dato.sex }}</td>
            </tr>
        </table>
    </div>
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
    <script>
        new Vue({
            el: '#app',
            data:{
                datos: []
            },
            methods: {
                getDatos: function() {
                    axios.get('data.json'). then(response => {
                        this.datos = response.data
                    })
                }
            },
                mounted: function (){
                    this.getDatos()
                }
        })
    </script>
</body>
</html>

Right here below I leave you the data.json that I invented for the example, both I put them in the same folder

[
    {
        "name": "Alfredo",
        "age": 28,
        "sex": "masculino"
    },
    {
        "name": "Jorge",
        "age": 20,
        "sex": "masculino"
    }
]

The following is the final aspect and it is clear within a table but it has no styles

Try it on your computer as I give it to you and it should be functional greetings.

    
answered by 10.03.2018 / 19:42
source
2

Hello my solution is on this side, insert the following code in your script and make the corresponding call. You must call the function by passing the variable that has the data in json format.

function jsonToHtmlTable(data) {

    data = JSON.parse(data);

    var table = document.createElement("table");
    var thead = table.createTHead();
    var tbody = table.createTBody();

    var col = [];
    for (var i = 0; i < data.length; i++) {
        for (var key in data[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    var cabecera = thead.insertRow(-1);

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



    for (var i = 0; i < data.length; i++) {

        tr = tbody.insertRow(-1);

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

    return table;

};
    
answered by 07.05.2018 в 17:26
1

Here is a small function in pure JavaScript that, by passing an array of objects and the id of a table, will fill the table dynamically. The code is commented (and could be reduced a little because it repeats), but here is a description of how it works:

  • Use .keys() to obtain the index keys of the first element of the array of objects (it is assumed that all objects will have the same keys).
  • A dynamic header row is created with the index keys (no matter what they are, you can try different JSONs and it will still work).
  • The array of objects is crossed, filling the cells with the data of the object.

Here you can see it working:

// estos datos los podrías obtener via AJAX 
var datos = [
  {
    "nombre": "Ana",
    "edad": 20,
    "Hobbie": "Cantar"
  },
  {
    "nombre": "Alberto",
    "edad": 23,
    "Hobbie": "Programar Videojuegos"
  }
];

// llama a la función que genera la tabla
crearTablaDesdeArrayObjetos(datos, "miTabla");

//---------------------------------------

function crearTablaDesdeArrayObjetos(misDatos, idTabla) {
  var claves = [];

  // generamos la cabecera basada en las claves del primer elemento
  if (misDatos.length > 0) {
    // con Object.keys(array) obtenemos las claves del objeto
    claves = Object.keys(misDatos[0]);
    // creamos una fila
    let fila = document.createElement("tr");
    // para cada clave
    for (let x = 0; x < claves.length; x++) {
      // creamos una celda y rellenamos los datos
      let celda = document.createElement("th");
      celda.textContent = claves[x];
      fila.append(celda);
    }
    // añadimos la fila a la tabla
    document.getElementById(idTabla).append(fila);
  }

  for (let x = 0; x < misDatos.length; x++) {
    let fila = document.createElement("tr");
    // para cada clave
    for (let y = 0; y < claves.length; y++) {
      // creamos una celda y rellenamos los datos
      let celda = document.createElement("td");
      celda.textContent = misDatos[x][claves[y]];
      fila.append(celda);
    }
    // añadimos la fila a la tabla
    document.getElementById(idTabla).append(fila);
  }
}
<table id="miTabla">
</table>
    
answered by 11.03.2018 в 04:56