如何在Javascript

时间:2017-08-30 04:44:23

标签: javascript json chart.js

我想将数据表转换为Json。我使用node.js 我有数据表:

 -------------------------------------
 |   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:

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创建堆积条形图.js。 感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用解决方案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>

希望这会对你有所帮助。

答案 1 :(得分:0)

表到json但是嵌套json的任何可能性。它将如何形成