Skip to content

Instantly share code, notes, and snippets.

@todofixthis
Created October 23, 2016 00:38
Show Gist options
  • Save todofixthis/56189b6f12c17763beeb5820217057bb to your computer and use it in GitHub Desktop.
Save todofixthis/56189b6f12c17763beeb5820217057bb to your computer and use it in GitHub Desktop.
Serialize form inputs into JSON, with support for `name[]` syntax.
(function($) {
$.extend($.fn, {
serializeJson: function() {
var payload = {},
regex = /^(\w+)\[(\d*)\]$/;
$.each($(this).serializeArray(), function(i, input) {
var res = input.name.match(regex);
if(res) {
if(! (res[1] in payload)) {
payload[res[1]] = [];
}
var array = payload[res[1]];
if(res[2] == '') {
array[array.length] = input.value;
} else {
// Ensure that the value gets inserted at exactly
// the right spot.
while(array.length < res[2]) {
array[array.length] = null;
}
array.splice(res[2], 0, input.value);
}
} else {
payload[input.name] = input.value;
}
});
return JSON.stringify(payload);
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment