jQuery: serialize a form to JSON

by Shawn Wood

HTML

<form action="#" method="post">
    <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email[][type]" id="email" />
        <input type="text" name="email[][test]" id="email" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email[][type]" id="email" />
        <input type="text" name="email[][test]" id="email" />
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" id="password" />
    </div>
    <p>
        <input type="submit" value="Send" />
    </p>
</form>

CSS

form div {
    margin-bottom: 0.5em;
}
form div label, form div input {
    display: block;
    margin-bottom: 0.3em;
}

JavaScript

$('form').submit(function (e) {
    e.preventDefault();
    var data = $(this).serializeJSON();
    //alert(data);
    console.log(data);
    var stringData = JSON.stringify(data);
    console.log(stringData)

    /* Object
        email: "value"
        name: "value"
        password: "value"
     */
});

/*!
  SerializeJSON jQuery plugin.
  https://github.com/marioizquierdo/jquery.serializeJSON
  version 2.4.2 (Oct, 2014)

  Copyright (c) 2014 Mario Izquierdo
  Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
  and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function ($) {
  "use strict";

  // jQuery('form').serializeJSON()
  $.fn.serializeJSON = function (options) {
    var serializedObject, formAsArray, keys, type, value, _ref, f, opts;
    f = $.serializeJSON;
    opts = f.optsWithDefaults(options); // calculate values for options {parseNumbers, parseBoolens, parseNulls}
    f.validateOptions(opts);
    formAsArray = this.serializeArray(); // array of objects {name, value}
    f.readCheckboxUncheckedValues(formAsArray, this, opts); // add {name, value} of unchecked checkboxes if needed

    serializedObject = {};
    $.each(formAsArray, function (i, input) {
      keys = f.splitInputNameIntoKeysArray(input.name);
      type = keys.pop(); // the last element is always the type ("string" by default)
      if (type !== 'skip') { // easy way to skip a value
        value = f.parseValue(input.value, type, opts); // string, number, boolean or null
        if (opts.parseWithFunction && type === '_') value = opts.parseWithFunction(value, input.name); // allow for custom parsing
        f.deepSet(serializedObject, keys, value, opts);
      }
    });
    return serializedObject;
  };

  // Use $.serializeJSON as namespace for the auxiliar functions
  // and to define defaults
  $.serializeJSON = {

    defaultOptions: {
      parseNumbers: false, // convert values like "1", "-2.33" to 1, -2.33
     ...