Armen Armen - 5 months ago 13
jQuery Question

Collect form all inputs data into structured json

I'm trying to collect html form inputs to JSON.

I was trying to realize it with jQuery

serializeArray
which works ok for simple input names, but in case I have multidimensional inputs name like

<input type="text" name="product[0][name]" >


as an output of
serializeArray
I have list of object like

var result = $('#myform').serializeArray();
console.log( result );

0: Object
name: "product[0][name]"
value: "product 1"
...
1: Object
name: "product[1][name]"
value: "product 2"
...
...


also tried with
JSON.stringify($('#myform').serializeArray());
but oputput again contain concated names as keys

[{"name":"product[0][name]","value":"product 1"}, ...


But I would like to parse it or use some other know function from jQuery or other library which will give me output in this way

{
product: [
0: {'name':'product 1'},
1: {'name':'product 1'},
2: {'name':'product 1'},
],
some_other_filed: [
0: {'key':'value'},
1: {'name':'value'}
]
}


Dose anyone know solution for this situation?

Answer

You could use jQuery serializeJSON plugin.

$('#myform').serializeJSON();
console.log( result );