i tried using some example, but somehow it is not working. please guide me.
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
td, th {
padding: 10px;
}
</style>
</head>
<body>
<h2>Convert JSON data into a html table using Javascript</h2>
<p>Click the following button to convert JSON results into HTML table</p><br>
<button id="btn" onclick="convert( )"> Click Here </button> <br>
<h3> Resulting Table: </h3>
<div id="container"></div>
<script>
function convert() {
// Sample JSON data
let jsonData = {
"data":[
{
"customer Name": "ganesh",
"ami":"T6767667",
"state":"closed",
"ssoId":"dhhhdhv",
"convId":"I90098890098",
"account number":"2233233"
},
{
"customer Name": "putta",
"ami":"T6767668",
"state":"closed",
"ssoId":"dhhhdhY",
"convId":"I90098890099",
"account number":"2233234"
}
],
"metadata":{
"": "",
"outcome":{
"status":200,
"code":0,
"type":"OK",
"message":""
}
}
};
let container = document.getElementById("container");
let table = document.createElement("table");
let cols = Object.keys(jsonData[0]);
let thead = document.createElement("thead");
let tr = document.createElement("tr");
cols.forEach((item) => {
let th = document.createElement("th");
th.innerText = item;
tr.appendChild(th);
});
thead.appendChild(tr);
table.append(tr)
jsonData.forEach((item) => {
let tr = document.createElement("tr");
let vals = Object.values(item);
vals.forEach((elem) => {
let td = document.createElement("td");
td.innerText = elem;
tr.appendChild(td);
});
table.appendChild(tr);
});
container.appendChild(table)
}
</script>
</body>
</html>
3
Answers
The code you provided seems almost correct, but there’s a small issue. You are trying to access j
sonData[0]
, but jsonData is not an array, it’s an object with a "data" property that contains the array you want to iterate through. You should access jsonData.data to access thearray.pls
I’ve used
jsonData.data
to access the array of data objects, and I’ve also added<thead>
for the table header row. Additionally, I’ve cleared the container before appending the table to ensure that the table updates when you click the button multiple times.Code Snippet
Yet another solution to create headers and rows from
jsonData.data
.Hope this helps!