话不多说,开整。
示例:
<body>
<form id="form1" runat="server">
<table id="Table">
<tr>
<th class="th">姓名</th>
<th class="th">年龄</th>
<th class="th">性别</th>
</tr>
<tr>
<td class="th">张三</td>
<td class="th">12</td>
<td class="th">男</td>
</tr>
<tr>
<td class="th">李四</td>
<td class="th">18</td>
<td class="th">男</td>
</tr>
<tr>
<td class="th">小红</td>
<td class="th">20</td>
<td class="th">女</td>
</tr>
</table>
<div>
<input type="button" value="转Json字符串" onclick="chang()" />
</div>
</form>
</body>
展示页面:
点击按钮将列表中的数据转换成JSON字符串,以下是js代码。
function chang() {
1、获取表中数据
var mytable = document.getElementById("Table");
2、新建json字符串,设置json格式
var JsonString = "";
JsonString += ("[");
3、循环添加
for (var i = 1; i < mytable.rows.length; i++) {
JsonString += ("{");
JsonString += ("\"Name\":" + "\"" + mytable.rows[i].cells[0].innerHTML + "\",");
JsonString += ("\"Age\":" + "\"" + mytable.rows[i].cells[1].innerHTML + "\",");
JsonString += ("\"Sex\":" + "\"" + mytable.rows[i].cells[2].innerHTML + "\"");
if (i == mytable.rows.length - 1) {
JsonString += ("}");
}
else {
JsonString += ("},");
}
}
JsonString += ("]");
4、打印
console.log(JsonString);
}
打印的数据: