Iterate through HTML table using jQuery, converting the data in the table into JSON

前端 未结 4 536
遇见更好的自我
遇见更好的自我 2020-12-10 09:37

I came across a case where I have to convert an HTML table data into JSON. In this process I have to iterate through the table and convert one by one (row) into an array and

相关标签:
4条回答
  • 2020-12-10 09:58

    You also need to convert the JavaScript array (also work on objects, strings, etc.) into a JSON serialized string.

    Add this to your page (will be added to jQuery soon):

    <script type="text/javascript" src="http://json.org/json2.js"></script>
    

    And then serialize your array:

    JSON.stringify(myTable)
    
    0 讨论(0)
  • 2020-12-10 10:02

    First as fredrik pointed out we need to include https://github.com/douglascrockford/JSON-js.

    Second we can use jQuery.fn.map and jQuery.fn.get to create an array of arrays (the tr:s) which contains the jQuery.fn.text content of the td elements:

    var AoA = $('table tr').map(function(){
        return [
            $('td',this).map(function(){
                return $(this).text();
            }).get()
        ];
    }).get();
    var json = JSON.stringify(AoA);
    
    0 讨论(0)
  • 2020-12-10 10:08

    Something like this? Fetching the content of each td into a myTable[rowIx][tableIx] array.

    var myTable = [];
    $('#myTable tr').each(function (i, tr) {
        var myTr = [];
    
        $('td', tr).each(function(j, td) {
            myTr.push($(td).html());
        });
    
        myTable.push(myTr);
    });
    
    0 讨论(0)
  • 2020-12-10 10:08

    I wrote a plugin for this, it has a few bells and whistles. Check it out at:

    http://www.fletchzone.com/post/jQuery-Convert-HTML-Table-to-JSON.aspx

    0 讨论(0)
提交回复
热议问题