如何在Javascript中将数据表转换为Json [英] How to convert Data table to Json in Javascript
本文介绍了如何在Javascript中将数据表转换为Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将数据表转换为Json。我使用node.js
我的数据表为:
I want to convert data table to Json. I use node.js I have Data Table as :
-------------------------------------
| Month | Name | Sum |
-------------------------------------
| January | John | 25 |
| February | Jane | 30 |
| February | John | 35 |
| February | Alex | 20 |
| March | Jane | 32 |
| March | John | 35 |
| March | Alex | 30 |
我想将数据转换为Json:
I want convert data to Json :
var data = [{
"Month": "January",
"Information": [{
"Name": "John",
"Sum": 25
}]
}, {
"Month": "February",
"Information": [{
"Name": "Jane",
"Sum": 30
}, {
"Name": "John",
"Sum": 35
}, {
"Name": "Alex",
"Sum": 20
}]
},{
"Month": "March",
"Information": [{
"Name": "Jane",
"Sum": 32
}, {
"Name": "John",
"Sum": 35
}, {
"Name": "Alex",
"Sum": 30
}]
}]
如何执行此操作。
我希望Json创建堆积的条形图chart.js。
谢谢。
How to do this. I want Json to create stacked bar chart.js. thanks.
推荐答案
在这里提供解决方案 https://jsfiddle.net/mou882tw/
var data = [];
var lastMonth = "";
var child = document.getElementsByTagName('tr');
var temp = {};
var th = child[0].children;
for(var i=1; i<child.length; i++){
var td = child[i].children;
if(lastMonth != td[0].textContent){
if( JSON.stringify(temp) != '{}')
data.push(temp);
temp = {};
temp["Information"] = [];
}
var innerJSON = {};
for(var j=0; j<td.length; j++){
if(j == 0){
temp[th[j].textContent] = td[j].textContent;
lastMonth = td[j].textContent;
} else {
innerJSON[th[j].textContent] = td[j].textContent;
}
}
temp["Information"].push(innerJSON);
if(i == (child.length -1)){
data.push(temp);
}
}
console.log(data);
<table>
<thead>
<tr>
<th>Month</th>
<th>Name</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td>February</td>
<td>Jane</td>
<td>30</td>
</tr>
<tr>
<td>February</td>
<td>John</td>
<td>35</td>
</tr>
<tr>
<td>February</td>
<td>Alex</td>
<td>20</td>
</tr>
<tr>
<td>March</td>
<td>Jane</td>
<td>32</td>
</tr>
<tr>
<td>March</td>
<td>John</td>
<td>35</td>
</tr>
<tr>
<td>March</td>
<td>Alex</td>
<td>30</td>
</tr>
</tbody>
</table>
希望这会帮助您。
这篇关于如何在Javascript中将数据表转换为Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文