Andrei Cristian Prodan Andrei Cristian Prodan - 2 months ago 5
jQuery Question

How do you JSON (instead of serialize) a form that has name="Item[][things]" without obtaining an object with null children?

This is a pretty specific issue and I can't find it online or I couldn't find a solution to it until now at least.

I have a form, that contains inputs that have:

name = "Item[][things]"
as in an item. Can't change that. I want to turn that into a JSON to send it to the server. I can't use serialize, I really need to turn it into a JSON.

This doesn't work with what I tried:
. Because my form contains name="Item[][differentOtherThings]", I get an array of nulls
[null, null, ..., null]

I added a serializeObject() custom method jquery-serialize-object to my project.

Any ideas on how I could JSON the form without the null issue?


see the bellow snippet

    var $myForm = $("form").eq(0);
    var str = JSON.stringify($myForm.serializeObject());
    var object = JSON.parse(str);

$.fn.serializeObject = function()
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[] !== undefined) {
            if (!o[].push) {
                o[] = [o[]];
            o[].push(this.value || '');
        } else {
            o[] = this.value || '';
    return o;
<script src=""></script>

   <p><input type="text"  name = "Item[][things]"></p>
   <p><input type="text"  name = "Item[][things1]"></p> 
   <p><input type="text"  name = "Item[][differentOtherThings]"></p>


  <button id="serialize">serialize</button>