HTML Table to JSON

前端 未结 7 1884
小鲜肉
小鲜肉 2020-11-29 06:56

I need to take table rows and convert to JSON.

Any ideas? I have this code here but it does not work.

function tableToJSON(tableID) {
    return $(t         


        
相关标签:
7条回答
  • 2020-11-29 07:33

    HTML:

    <table id="answered">
    <tbody>
        <tr>
          <td data-id="user.email">email@email.com</td>
          <td data-id="meme.yodawg">Yo Dog! I Heard you liked answers, so I answered your question, with a method wrapped in a jQuery plugin!</td>
        </tr>
    </tbody>
    </table>
    

    jQuery:

    (function($) {
    
      $.extend($.fn, {
    
        tableRowsToJSONWithFilter : function (filter) {
          var tableSelector = this, item, attr, data, _JSON = [];
          if (typeof(tableSelector) !== 'object') {
            return new Error('Invalid tableSelect!');
          };
          $(tableSelector, 'tr').each(function(index, tr) {
            item = {};
            $('td', $(this)).each(function(index, td) {
              attr = $(td).attr('data-id');
              data = $(td).text();
              if (attr !== undefined && data !== '' && filter && new RegExp(filter, 'i').test(attr)) {
                item[attr] = data;
              };
            });
            _JSON.push(item);
          });
          return _JSON;
        }
    
      })
    
    })(jQuery);
    

    Usage:

    $('#answered').tableRowsToJSONWithFilter('yodawg');
    
    0 讨论(0)
提交回复
热议问题