本文介绍了以json格式获取表数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我要获取json格式的表数据的地方是我的表
Hello everyone I'm trying to get table data in json format here is my table
<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
using the below 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开始.
but i want to add key to every value and the number should start from one and not zero.
我有一组欲望结果,它应该看起来像这样 感谢您的帮助
i have a set of desire result and it should look like this any help is appreciated
{ "1": { no: "1", name:"Jhon One", lastname "Doe one" } , "2": { no: "1", name:"Jhon two", lastname "Doe two" } }这是我尝试过的fiddel链接
here is the fiddel link which i have tried
jsfiddle/k228n2bn/
推荐答案只需更改以下行
otArr.push('"' + e + '": {' + itArr.join(',') + '}');到
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');括号将把值添加为数字而不是字符串.
The parenthesis will add the values as numbers not strings.
此外,为内部对象键添加keys数组.
Also, add keys array for internal object keys.
function html2json() { var json = '{'; var otArr = []; // var i = 1; var tbl2 = $('table tbody tr').each(function(e) { x = $(this).children(); var itArr = []; var keys = ['no','name','lastname']; x.each(function(i) { itArr.push('"' + keys[i] + '":"' + $(this).text() + '"'); }); otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}'); }) json += otArr.join(",") + '}' return json; }更多推荐
以json格式获取表数据
发布评论