Serialize complex form to JSON object using jQuery

Viewed 18295

I've been searching for hours for this and haven't found an answer. Please read through the whole question before flaming! :)

I have a form similar to this:

<form id="sample">
 <input name="name" type="text" value="name value" />

 <input name="phone[0][type]" type="text" value="cell" />
 <input name="phone[0][number]" type="text" value="000" />

 <input name="phone[1][type]" type="text" value="home" />
 <input name="phone[1][number]" type="text" value="111" />
</form>

And need to be able to serialize it to this:

{
 name: 'name value',

 phone: [
  {
   type: 'cell',
   number: '000'
  },
  {
   type: 'home',
   number: '111'
  }
 ]
}

I have tried most answers on SO including jquery-json libraries and most of them return something like this:

{
 'name': 'name value',
 'phone[0][type]': 'cell',
 'phone[0][number]': '000',
 'phone[1][type]': 'home',
 'phone[1][number]': '111',
}

This is something I cannot use! :P

Thanks everyone in advance.

6 Answers
Related