Mono Jamoon
Mono Jamoon

Reputation: 4607

Converting table data into JSON

I am trying to convert data present in a HTML table into JSON so that it could be processed accordingly on the server side. I am able to serialize the data, but the results, at best, generate distinct arrays of data which aren't linked directly. Like: This is the form I am using:

<form id="nameGenderForm">
    <table id="nameGenderTable">

        <tr>
            <th >Name</th>
            <th >Gender</th>
        </tr>


            <tr>
                <td><input type="text" name="studentName"></td>
                <td>
                    <select name="studentGender">
                        <option value="male">male</option>
                        <option value="female">female</option>
                    </select>
                </td>
            </tr>

            <tr>
                <td><input type="text" name="studentName"></td>
                <td>
                    <select name="studentGender">
                        <option value="male">male</option>
                        <option value="female">female</option>
                    </select>
                </td>
            </tr>
        </table>
    <input type="submit" />
</form>

The script to serialize the data is:

$("#nameGenderForm").submit(function(event){
    event.preventDefault();

    var rawData=$('#nameGenderForm').serializeFormJSON();
    var formData=JSON.stringify(rawData);
    console.log(formData);
});

serializeFormJSON() is what I got after going through few pages of StackOverFlow:

(function($) {
$.fn.serializeFormJSON = function() {
var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};
})(jQuery);

By using all these I am able to get a JSON something like this:

{"studentName":["kenpachi","orihime"],"studentGender":["male","female"]}

I tried many ways to get them in a name-gender format but every way yields the same result. Two distinct arrays. Using form for each didn't help either. Is there any way to get the data in name-gender array like this:

{"studentName":"kenpachi","studentGender":"male"},{"studentName":"orihime","studentGender":"female"}

Please advise.

Upvotes: 3

Views: 22262

Answers (4)

roshan siva
roshan siva

Reputation: 1

 function tableToArray(table) {
                    var headers = [];
                    var data = []; // first row needs to be headers var headers = []; 
                    for (var i = 0; i < table.rows[0].cells.length; i++) {
                        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
                    }
                    // go through cells 
                    for (var i = 1; i < table.rows.length; i++) {
                        var tableRow = table.rows[i]; var rowData = {};
                        for (var j = 0; j < tableRow.cells.length; j++) {
                            rowData[headers[j]] = tableRow.cells[j].innerHTML;
                        } data.push(rowData);
                    }
                    return data;
                }

                function tableToJson(table) {
                    var headers = [];
                    var data = '{[';
                    for (var i = 0; i < table.rows[0].cells.length; i++) {
                        headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
                    }

                    for (var i = 1; i < table.rows.length; i++) {
                        var tableRow = table.rows[i]; var rowData = {};
                        for (var j = 0; j < tableRow.cells.length; j++) {
                            rowData[headers[j]] = tableRow.cells[j].innerHTML;
                        } data = (data + JSON.stringify(rowData) + ",");
                    }
                    return data.slice(0, -1) + "]}";
                }

Upvotes: 0

Zain Shaikh
Zain Shaikh

Reputation: 6043

Here you go with demo, made slight changes pointed below:

looped over each table row, and found input, textarea and select type elements, serialized them, converted to object and then pushed to an array.

    var o = [];
    $(this).find('tr').each(function() {
        var $this = $(this);
        var $elements = $this.find('input, textarea, select')
        if ($elements.size() > 0) {
            var serialized = $elements.serialize();
            var item = $.toDictionary( serialized );
            o.push(item);
        }
    });

P.S. added a new function to jquery library named toDictionary, so make sure you include that in your code as well.

$.toDictionary function

(function($) {
    $.extend({
        toDictionary: function(query) {
            var parms = {};
            var items = query.split("&"); // split
            for (var i = 0; i < items.length; i++) {
                var values = items[i].split("=");
                var key = decodeURIComponent(values.shift());
                var value = values.join("=")
                parms[key] = decodeURIComponent(value);
            }
            return (parms);
        }
    })
})(jQuery);

Upvotes: 5

AKX
AKX

Reputation: 168843

I'd do something like this jsFiddle -- that is, loop through each of the rows and gather the data from the inputs, then push each object into the result array.

You may want to use a class on the inputs instead, as it is likely to be faster than looking up via the currently pretty cumbersome :input[name=xyz] selector.

Upvotes: 0

VVV
VVV

Reputation: 7593

Give them the same name but as an array

for example

name="first[studentName]" and name="first[studentGender]"

then for your second inputs

name="second[studentName]" and name="second[studentGender]"

Also, maybe serializeArray would help.

Upvotes: 0

Related Questions