Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example:

Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]

My goal is to create a table with the headers (num, name, phone)

Is there a way to achieve this using JavaScript without relying on JQuery?

Answer №1

var students = [{id: 1, name: 'John', grade: 85}, {id: 2, name: 'Emily', grade: 92}];

function addTableHeaders(table, keys) {
  var row = table.insertRow();
  for( var i = 0; i < keys.length; i++ ) {
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(keys[i]));
  }
}

var table = document.createElement('table');
for( var i = 0; i < students.length; i++ ) {

  var student = students[i];
  if(i === 0 ) {
    addTableHeaders(table, Object.keys(student));
  }
  var row = table.insertRow();
  Object.keys(student).forEach(function(k) {
    console.log(k);
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(student[k]));
  })
}

document.getElementById('classroom').appendChild(table);
<div id="classroom"></div>

Answer №2

Follow the steps below to generate a table using JSON data. First, you need to copy the provided JavaScript and HTML code.

Javascript

<script type="text/javascript">
function convertJsonToTable(jsonData) {
  var parsedJson = JSON.parse(jsonData);
  var columns = [];
  var tableHeader = "<thead><tr>";
  for (key in parsedJson[0]) {
    columns.push(key);
    tableHeader += "<th>" + key + "</th>";
  }
  tableHeader += "</tr></thead>";
  document.getElementById("tableID").innerHTML = tableHeader;
  var tableRows = '<tbody>';
  for (var i = 0; i < parsedJson.length; i++) {
    var rowData = parsedJson[i];
      var jsonRow = rowData;
      var row = "<tr>"
        for (data in rowData) {
          var value = rowData[data];
          if (value != null) {
            var stringValue = value.toString();
            var replaceStr = "<\\";
            row += "<td><p>" + stringValue.split('<').join('&lt;') + "</p></td>";
          } else {
            row += "<td><p>null</p></td>";
          }
        }
      row += "</tr>"
      tableRows += row;
  }
  tableRows += '</tbody>';
  document.getElementById("tableID").innerHTML += tableRows;
}
</script>

HTML

<table id="tableID" class="table"></table>

Call the Method

convertJsonToTable("YOUR_JSON");

Example

var jsonData = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';

convertJsonToTable(jsonData);

Answer №3

fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => generateTable(data)).catch(error=>console.error(error))

const generateTable = (data) => {
  const tableData = data;
  
  const headerData = Object.keys(tableData[0]);
  
  const table = document.createElement('table');
  
  const tr = table.insertRow(-1);
 
  
  for(let i=0; i<headerData.length; i++){
    const th = document.createElement('th');
    th.innerHTML = headerData[i];
    tr.appendChild(th)
  }
  
  for(let i=0; i<tableData.length; i++){
    const newRow = table.insertRow(-1);
        const item = tableData[i];
    for(let key in item) {
        const td = document.createElement('td');
      td.innerHTML = item[key];
      newRow.appendChild(td);
    }
}
  
  document.body.appendChild(table);
}

Answer №4

Code Snippet in Javascript

var _table_ = document.createElement('table'),
    _tr_ = document.createElement('tr'),
    _th_ = document.createElement('th'),
    _td_ = document.createElement('td');

// Function to create an HTML table from JSON data fetched via a RESTful service.
 function buildHtmlTable(arr) {
     var table = _table_.cloneNode(false),
         columns = addAllColumnHeaders(arr, table);
     for (var i=0, maxi=arr.length; i < maxi; ++i) {
         var tr = _tr_.cloneNode(false);
         for (var j=0, maxj=columns.length; j < maxj ; ++j) {
             var td = _td_.cloneNode(false);
                 cellValue = arr[i][columns[j]];
             td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
             tr.appendChild(td);
         }
         table.appendChild(tr);
     }
     return table;
 }

 // Adds a header row to the table and returns the set of columns by combining keys from all records.
 function addAllColumnHeaders(arr, table)
 {
     var columnSet = [],
         tr = _tr_.cloneNode(false);
     for (var i=0, l=arr.length; i < l; i++) {
         for (var key in arr[i]) {
             if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
                 columnSet.push(key);
                 var th = _th_.cloneNode(false);
                 th.appendChild(document.createTextNode(key));
                 tr.appendChild(th);
             }
         }
     }
     table.appendChild(tr);
     return columnSet;
 }


document.body.appendChild(buildHtmlTable([
    {"num" : "6", "name" : "me", "phone" : "7"},
    {"num" : "8", "name" : "him", "phone" : "9"}
]));

Styling with CSS in the Code Snippet

  th, td {
      border: 1px solid;
  }
  th {
      font-weight : bold
  }

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

Please provide an explanation of how babel and node.js are interconnected within the ReactJS framework

As a beginner in ReactJS, I'm curious about the role of Node.js in the React ecosystem. Can someone please explain its importance to me? ...

Issues with the functionality of the asynchronous socket.io JavaScript callback are being experienced

I am facing an issue with my JavaScript code that involves querying data from a database using Node.js and Socket.io. Currently, I have implemented setTimeout() functions to make it work, but I want to switch to using callbacks for better reliability. Howe ...

What type of codec does JSON Facebook use for retrieving information?

Recently, I obtained a JSON file from Facebook containing all of my personal information. While the JSON data itself does not pose an issue, I am facing a problem even before beginning to manipulate the files. The challenge lies in determining the correct ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

Converting a json array into an object by utilizing moshi in conjunction with Retrofit and Kotlin

I am currently working on parsing a JSON Array using the Moshi Library with Kotlin Coroutines. Here is the code snippet I am using: fun retrofitIndia(baseUrl: String): Retrofit = Retrofit.Builder() .client(clientIndia) .baseUrl(baseUrl) ...

Displaying Dynamic Content in React Table Rows Based on Conditions

I'm populating a table with multiple rows using props. If a returned prop is an empty string "" , I want to exclude that row from rendering. <Table.Body> <Table.Row> <Table.Cell>Producer</Table.Cell> ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

Step-by-step guide on displaying SVG text on a DOM element using Angular 8

I have a FusionChart graph that I need to extract the image from and display it on the same HTML page when the user clicks on the "Get SVG String" button. I am able to retrieve the SVG text using this.chart.getSVGString() method, but I'm unsure of ho ...

Using Python to Populate an Array Inside a JSON Object

The JSON below shows a structure with file name and function details: post = { "file_name" : file_name, "function" : [{ "func_name" : func_name, "start_line" : start_line, "end_line" : end_line }] } In my Python script, I am attempti ...

Retrieving data from a dynamic array using jQuery

Within my code, I am working with an array that contains IDs of div elements (specifically, the IDs of all child div elements within a parent div with the ID of #area): jQuery.fn.getIdArray = function () { var ret = []; $('[id]', this).each(fu ...

Learning how to interpret a JSON string in VB6

I am currently working on a project in VB6 where I need to call a web service that returns a JSON string as a response. After successfully storing the response in a string, my next task is to extract each parameter individually. Could someone provide gui ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Issues with the functionality of the node.js socket.io listener

I am currently experiencing an issue with private messaging in my chat application. The private message functionality does not seem to be working as expected. Below is the code snippet from the app.js file: var express = require('express'),htt ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Activate jqGrid's navigation bar save icon when the ondblClickRow event is triggered

After setting the jqGrid row edit on the ondblClickRow event, how can I enable the save icon on the navigation bar when a row is double clicked? ondblClickRow: function (rowid) { jQuery(this).jqGrid('editRow', rowid, true, null, null); ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Inspecting a substring of an element dynamically added in VueJs

When I click a button in my form, it adds a new line. The challenge is making sure that each new line evaluates independently and correctly. In this case, the task involves checking the first 2 digits of a barcode against a dataset to determine a match or ...

When the response is manually terminated, the next middleware layer in express.js is invoked

I recently noticed an unusual occurrence: Even though I am explicitly ending the request using res.json() in one express middleware, the request still cascades down to the next middleware. It is important to mention that I am not utilizing next() anywhere ...

Show a modal component from another component in Angular 2

As a newcomer to Angular, I'm working on a modal component that changes from hiding to showing when a button with (click) is clicked. The goal is to integrate this modal into my main component, allowing me to display the modal on top of the main conte ...