以json格式获取表数据

编程入门 行业动态 更新时间:2024-10-23 16:29:14
本文介绍了以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格式获取表数据

本文发布于:2023-10-12 17:19:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   数据   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!