How to convert jQuery.serialize() data to JSON object?

Viewed 108580

Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to be able to convert the form data in to a JSON object to recreate some other informative tables. So tell me a better way to get the serialize string converted as a JSON object.

<form id='sampleform'>
    <input name='MyName' type='text' /> // Raf

    <!--array input fields below-->
    <input name='friendname[]' type='text' /> // Bily
    <input name='fiendemail[]' type='text' /> // bily@someemail.com

    <!--duplicated fields below to add more friends -->
    <input name='friendname[]' type='text' /> // Andy
    <input name='fiendemail[]' type='text' /> // Andy@somwhere.com

    <input name='friendname[]' type='text' /> // Adam
    <input name='fiendemail[]' type='text' /> // Adam@herenthere.com
</form>

The jquery method applied to get the data

var MyForm = $("#sampleform").serialize();
/** result : MyName=Raf&friendname[]=Billy&fiendemail[]=bily@someemail.com&friendname[]=Andy&fiendemail[]=Andy@somwhere.com&friendname[]=Adam&fiendemail[]=Adam@herenthere.com
*/

how do I make this data in to a JSON object? which should have the following example JSON data from the above form.

{
    "MyName":"raf",
    "friendname":[
        {"0":"Bily"},
        {"1":"Andy"},
        {"2":"Adam"}
    ],
    "friendemail":[
        {"0":"bily@someemail.com"},
        {"1":"Andy@somwhere.com"},
        {"2":"Adam@herenthere.com"}
    ]
}
13 Answers

if you can use ES6, you could do

const obj = arr.reduce((acc, {name, value}) => ({...acc, [name]: value}), {})

for a serialized array works very well.

Using the power of reducing function!

$(form).serializeArray().reduce(function (output, value) {
        output[value.name] = value.value

        return output
}, {})

With all Given Answer there some problem which is...

If input name as array like name[key], but it will generate like this

 name:{
   key : value
 }

For Example : If i have form like this.

    <form>
        <input name="name" value="value" >
        <input name="name1[key1]" value="value1" >
        <input name="name2[key2]" value="value2" >
        <input name="name3[key3]" value="value3" >
    </form>

Then It will Generate Object like this with all given Answer.

Object {
    name : 'value',
    name1[key1] : 'value1',
    name2[key2] : 'value2',
    name3[key3] : 'value3', 
}

But it have to Generate like below,anyone want to get like this as below.

Object {
    name : 'value',
    name1 : {
        key1 : 'value1'
    },
    name2 : {
        key2 : 'value2'
    },
    name3 : {
        key2 : 'value2'
    }
}

Then Try this below js code.

(function($) {
  $.fn.getForm2obj = function() {
    var _ = {};
    $.map(this.serializeArray(), function(n) {
      const keys = n.name.match(/[a-zA-Z0-9_]+|(?=\[\])/g);
      if (keys.length > 1) {
        let tmp = _;
        pop = keys.pop();
        for (let i = 0; i < keys.length, j = keys[i]; i++) {
          tmp[j] = (!tmp[j] ? (pop == '') ? [] : {} : tmp[j]), tmp = tmp[j];
        }
        if (pop == '') tmp = (!Array.isArray(tmp) ? [] : tmp), tmp.push(n.value);
        else tmp[pop] = n.value;
      } else _[keys.pop()] = n.value;
    });
    return _;
  }
  console.log($('form').getForm2obj());
  $('form input').change(function() {
    console.clear();
    console.log($('form').getForm2obj());
  });
})(jQuery);
console.log($('form').getForm2obj());
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form>
  <input name="name" value="value">
  <input name="name1[key1]" value="value1">
  <input name="name2[key2]" value="value2">
  <input name="name3[key3]" value="value3">
  <input type="checkbox" name="name4[]" value="1" checked="checked">
  <input type="checkbox" name="name4[]" value="2">
  <input type="checkbox" name="name4[]" value="3">
</form>

if you are using ajax requests then no need to make it json-object only $('#sampleform').serialize() works excellently or if you have another purpose here is my solution:

var formserializeArray = $("#sampleform").serializeArray();   
var jsonObj = {};
jQuery.map(formserializeArray , function (n, i) {
    jsonObj[n.name] = n.value;
});

Use JSON.stringify() and serializeArray():

console.log(JSON.stringify($('#sampleform').serializeArray()));

Related