Sunday, 19 February 2017

jQuery code to convert table data into JSON format


Below code converts table data into JSON format.


        function actionSubmit(){
//.messager.alert('Data Saved');

$(document).ready(function(){

  ResUtilObj = {rows: []};

  $('.datagrid-btable').find('tr').each(function() {

rowObj = {};

$(this).find('td').each(function() {

rowObj[$(this).attr("Field")] = $(this).text();

});

ResUtilObj.rows.push(rowObj);

});

console.log(JSON.stringify(ResUtilObj));
});

        }


Main points on the above code

$('.datagrid-btable').find('tr').each(function() { });  - This will loop through each record in the tr tag

$(this).find('td').each(function() {}); - This will loop through each td element in the td tag

ResUtilObj represents in the main table object, it is initialized with rows array object.

rowObj = {}; represents the each field and value in the row.

ResUtilObj.rows.push(rowObj); pushes each row into rows array object

$(this).attr("Field") -  is used to read each field attribute value in the <td field=""> markup

Finally, JSON.stringify(ResUtilObj) is used to convert the array object into JSON string.



No comments:

Post a Comment