使用D3将嵌套的JSON文件转换为表

时间:2018-03-22 18:23:21

标签: javascript json d3.js

我的JSON数据类似于下面显示的数据。我想使用D3.js将相同的数据转换为表格,任何人都可以帮助我吗?

JSON数据:

{
    "items": [
        {
        "tableName": "incidents",
        "count": 20000,
        "columnNames": [
            "id",
            "subject",
            "category"
        ],
        "rows": [
            [
                "61",
                "Test",
                null
            ],
            [
                "65",
                "TEST 2",
                null
            ]...
}

输出:

Id Subject Category

61  TEST 1  Null

65  TEST 2  Null

1 个答案:

答案 0 :(得分:0)

根据您的数据:

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>

来源:http://bl.ocks.org/jfreels/6734025