Reputation: 11
I have JSON
data similar to the one shown below. I would like to convert the same data into a table using D3.js
can anyone help me on this?
JSON Data:
{
"items": [
{
"tableName": "incidents",
"count": 20000,
"columnNames": [
"id",
"subject",
"category"
],
"rows": [
[
"61",
"Test",
null
],
[
"65",
"TEST 2",
null
]...
}
Output:
Id Subject Category
61 TEST 1 Null
65 TEST 2 Null
Upvotes: 0
Views: 1000
Reputation: 1836
Based on your data:
var data = {
"items": [
{
"tableName": "incidents",
"count": 20000,
"columnNames": [
"id",
"subject",
"category"
],
"rows": [
[
"61",
"Test",
null
],
[
"65",
"TEST 2",
null
],
[
"67",
"TEST 3",
"not null"
]
]
}
]
}
function tabulate(data, columns) {
var table = d3.select('body').append('table')
var thead = table.append('thead')
var tbody = table.append('tbody');
// append the header row
thead.append('tr')
.selectAll('th')
.data(columns).enter()
.append('th')
.text(function (column) { return column; });
// create a row for each object in the data
var rows = tbody.selectAll('tr')
.data(data.items[0].rows)
.enter()
.append('tr');
// create a cell in each row for each column
var cells = rows.selectAll('td')
.data(function (row,i) {return row; })
.enter()
.append('td')
.text(function (d) { return d; });
return table;
}
// render the table(s)
tabulate(data, data.items[0].columnNames); // data, columns table
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
Source: http://bl.ocks.org/jfreels/6734025
Upvotes: 1