以json格式获取表数据 [英] Get Table data in json format

查看:225
本文介绍了以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

https://jsfiddle.net/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格式获取表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆