How to get handson table data in json format with column header as key

user4736585 picture user4736585 · Apr 24, 2015 · Viewed 15.4k times · Source

I have handsontable and I want to get data enter on handsontable cell into server side. I have tried to ran below code but data is not in expected format. I was expecting to get the data in pure json format as column header as key.

Html code

<div class="handsontable" id="example"></div>
<input type="button" name="submit" value="submit" onclick="submitForm()" />

code for creating the handsontable

   $(document).ready(function () {
       $('#example').handsontable({
           startRows: 2,
           startCols: 2,
            rowHeaders: true,
            colHeaders: true,
            contextMenu: true,
       });
   });

code for extracting the information from handsontable

   function submitForm(){
        var $container = $('#example');
        var htContents = JSON.stringify($container.handsontable('getData'));
        alert(htContents);
    }

Currently handsontable has 2 rows and 2 column. Now if I press the button with cell value (1,1)=11,(1,2)=12,(2,1)=21 and (2,2)=22, result I am getting is in alert window

[["11","12"],["21","22"]]

But result I am expecting is

 [{"A":"11","B":"12"},{"A":"21","B":"22"}] 

where A and B is column header.

Answer

bluebinary picture bluebinary · Jun 21, 2016

For others who didn't discover the answer immediately, see @hakuna1811's comment above that since version 0.20.0 of Handsontable the .getSourceData() call should be used instead if you want to get your data back in the same format as you provided it - for example as an array of objects. It is not clear why the .getData() call's behavior was modified and it is not explained in the related GitHub issue noted in @hakuna1811's comment, but at least we have a working solution - thanks again to @hakuna1811 for the answer - it saved a lot of hunting around!