大家好,我试图让这里JSON格式表数据是用我的表获取JSON格式表数据
<table>
<thead>
<tr>
<th>srno</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jhon One</td>
<td>Doe one</td>
</tr>
<tr>
<td>2</td>
<td>Jhon two</td>
<td>Doe Two</td>
</tr>
</tbody>
</table>
<button>
convert
</button>
这我得到的结果是这样的
{
"0": {
"1",
"Jhon One",
"Doe one"
}
,
"1": {
"2",
"Jhon two",
"Doe Two"
}
}
以下javascript
$("button").click(function() {
var json = html2json();
alert(json);
});
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + e + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
但我想为每个值添加键,数字应该从1开始而不是0。
我有一组欲望的结果,它应该是这样的 任何帮助表示赞赏
{
"1": {
no: "1",
name:"Jhon One",
lastname "Doe one"
}
,
"2": {
no: "1",
name:"Jhon two",
lastname "Doe two"
}
}
这里是我曾尝试fiddel链接
https://jsfiddle.net/k228n2bn/
我希望[这](https://stackoverflow.com/questions/9927126/how-to-convert-the-following-table-to-json-with-javascript)计算器链接可以帮助你 – hasan
通过字符串连接来构建JSON不是一个好主意。 sonicblis和Félix已经做到了正确的方式。 – Langdon