Jquery Serialize Form To Object

JQuery serialize method creates a text string in standard URL-encoded notation.You can use this method on any individually jQuery object which is form controls, such as input, textarea, and select.

  1. Lol kids these days with their fancy jQuery. The JSON object is part of Javascript's built-in objects. Has nothing to do with jQuery. – devius Nov 13 '15 at 18:27 1.
  2. There is serialize and serializeArray but no serializeObject. An object is a great representation of the form values. There is an external library.
Active29 days ago

How do I convert all elements of my form to a JavaScript object?

I'd like to have some way of automatically building a JavaScript object from my form, without having to loop over each element. I do not want a string, as returned by $('#formid').serialize();, nor do I want the map returned by $('#formid').serializeArray();


48 Answers

12 next

serializeArray already does exactly that. You just need to massage the data into your required format:

Watch out for hidden fields which have the same name as real inputs as they will get overwritten.


Current source is on GitHub and bower.

$ bower install jquery-serialize-object

The following code is now deprecated.

The following code can take work with all sorts of input names; and handle them just as you'd expect.

For example:

Usage

The Sorcery (JavaScript)



A fixed version of Tobias Cohen's solution. This one correctly handles falsy values like 0 and '.

And a CoffeeScript version for your coding convenience:

Form Serialize Jquery


I like using Array.prototype.reduce because it's a one-liner, and it doesn't rely on Underscore.js or the like:

This is similar to the answer using Array.prototype.map, but you don't need to clutter up your scope with an additional object variable. One-stop shopping.

IMPORTANT NOTE: Forms with inputs that have duplicate name attributes are valid HTML, and is actually a common approach. Using any of the answers in this thread will be inappropriate in that case (since object keys must be unique).


All of these answers seemed so over the top to me. There's something to be said for simplicity. As long as all your form inputs have the name attribute set this should work just jim dandy.


If you are using Underscore.js you can use the relatively concise:


There really is no way to do this without examining each of the elements. What you really want to know is 'has someone else already written a method that converts a form to a JSON object?' Something like the following should work -- note that it will only give you the form elements that would be returned via a POST (must have a name). This is not tested.


Ok, I know this already has a highly upvoted answer, but another similar question was asked recently, and I was directed to this question as well. I'd like to offer my solution as well, because it offers an advantage over the accepted solution: You can include disabled form elements (which is sometimes important, depending on how your UI functions)

Here is my answer from the other SO question:

Initially, we were using jQuery's serializeArray() method, but that does not include form elements that are disabled. We will often disable form elements that are 'sync'd' to other sources on the page, but we still need to include the data in our serialized object. So serializeArray() is out. We used the :input selector to get all input elements (both enabled and disabled) in a given container, and then $.map() to create our object.

Note that for this to work, each of your inputs will need a name attribute, which will be the name of the property of the resulting object.

That is actually slightly modified from what we used. We needed to create an object that was structured as a .NET IDictionary, so we used this: (I provide it here in case it's useful)

I like both of these solutions, because they are simple uses of the $.map() function, and you have complete control over your selector (so, which elements you end up including in your resulting object). Also, no extra plugin required. Plain old jQuery.


This function should handle multidimensional arrays along with multiple elements with the same name.

I've been using it for a couple years so far:



One-liner (no dependencies other than jQuery), uses fixed object binding for function passsed to map method.

What it does?

suitable for progressive web apps (one can easily support both regular form submit action as well as ajax requests)


With all Given Answer there some problem which is..., If input name as array like name[key], but it will generate like this

For Example : If i have form like this.

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

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

Then Try this below js code.



Simplicity is best here. I've used a simple string replace with a regular expression, and they worked like a charm thus far. I am not a regular expression expert, but I bet you can even populate very complex objects.



Jquery Serialize Form Data

Using maček's solution, I modified it to work with the way ASP.NET MVC handles their nested/complex objects on the same form. All you have to do is modify the validate piece to this:

This will match and then correctly map elements with names like:

And


I found a problem with Tobias Cohen's code (I don't have enough points to comment on it directly), which otherwise works for me. If you have two select options with the same name, both with value=', the original code will produce 'name':' instead of 'name':[',']

I think this can fixed by adding ' || o[this.name] '' to the first if condition:


the simplest and most accurate way i found for this problem was to use bbq plugin or this one (which is about 0.5K bytes size).

it also works with multi dimensional arrays.


There is a plugin to do just that for jQuery, jquery.serializeJSON. I have used it successfully on a few projects now. It works like a charm.


I prefer this approach because: you don't have to iterate over 2 collections, you can get at things other than 'name' and 'value' if you need to, and you can sanitize your values before you store them in the object (if you have default values that you don't wish to store, for example).

Use like so:

Only tested in Firefox.


Turn anything into an object (not unit tested)

The output of test:

on

will yield:


I found a problem with the selected solution.

When using forms that have array based names the jQuery serializeArray() function actually dies.

I have a PHP framework that uses array-based field names to allow for the same form to be put onto the same page multiple times in multiple views. This can be handy to put both add, edit and delete on the same page without conflicting form models.

Since I wanted to seralize the forms without having to take this absolute base functionality out I decided to write my own seralizeArray():

Please note: This also works outside of form submit() so if an error occurs in the rest of your code the form won't submit if you place on a link button saying 'save changes'.

Also note that this function should never be used to validate the form only to gather the data to send to the server-side for validation. Using such weak and mass-assigned code WILL cause XSS, etc.


I had the same problem lately and came out with this .toJSON jQuery plugin which converts a form into a JSON object with the same structure. This is also expecially useful for dynamically generated forms where you want to let your user add more fields in specific places.

The point is you may actually want to build a form so that it has a structure itself, so let's say you want to make a form where the user inserts his favourite places in town: you can imagine this form to represent a <places>...</places> XML element containing a list of places the user likes thus a list of <place>...</place> elements each one containing for example a <name>...</name> element, a <type>...</type> element and then a list of <activity>...</activity> elements to represent the activities you can perform in such a place. So your XML structure would be like this:

How cool would it be to have a JSON object out of this which would represent this exact structure so you'll be able to either:

  • Store this object as it is in any CouchDB-like database
  • Read it from your $_POST[] server side and retrive a correctly nested array you can then semantically manipulate
  • Use some server-side script to convert it into a well-formed XML file (even if you don't know its exact structure a-priori)
  • Just somehow use it as it is in any Node.js-like server script

Jquery Serialize Form To Object Download

Object

OK, so now we need to think how a form can represent an XML file.

Of course the <form> tag is the root, but then we have that <place> element which is a container and not a data element itself, so we cannot use an input tag for it.

Here's where the <fieldset> tag comes in handy! We'll use <fieldset> tags to represent all container elements in our form/XML representation and so getting to a result like this:

As you can see in this form, we're breaking the rule of unique names, but this is OK because they'll be converted into an array of element thus they'll be referenced only by their index inside the array.

At this point you can see how there's no name='array[]' like name inside the form and everything is pretty, simple and semantic.

Now we want this form to be converted into a JSON object which will look like this:

To do this I have developed this jQuery plugin here which someone helped optimizing in this Code Review thread and looks like this:

I also made this one blog post to explain this more.

This converts everything in a form to JSON (even radio and check boxes) and all you'll have left to do is call

I know there's plenty of ways to convert forms into JSON objects and sure .serialize() and .serializeArray() work great in most cases and are mostly intended to be used, but I think this whole idea of writing a form as an XML structure with meaningful names and converting it into a well-formed JSON object is worth the try, also the fact you can add same-name input tags without worrying is very useful if you need to retrive dynamically generated forms data.

I hope this helps someone!


I coded a form to a multidimensional JavaScript object myself to use it in production. The result is https://github.com/serbanghita/formToObject.js.


I like samuels version, but I believe it has a small error. Normally JSON is sent as

{'coreSKU':'PCGUYJS','name_de':'whatever',...

NOT as

[{'coreSKU':'PCGUYJS'},{'name_de':'whatever'},...

so the function IMO should read:

and to wrap it in data array (as commonly expected, too), and finally send it as astringApp.stringify( {data:App.toJson( '#cropform :input' )} )

For the stringify look at Question 3593046 for the lean version, at json2.js for the every-eventuality-covered version. That should cover it all :)


For a quick, modern solution, use the JSONify jQuery plugin. The example below is taken verbatim from the GitHub README. All credit to Kushal Pandya, author of the plugin.

Given:

Running:

Produces:

If you want to do a jQuery POST with this JSON object:



Another answer

FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData


I wouldn't use this on a live site due to XSS attacks and probably plenty of other issues, but here's a quick example of what you could do:


protected by Josh CrozierMay 30 '14 at 20:18

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged javascriptjqueryjsonserialization or ask your own question.

As seen on StackOverflow: Convert forms to JSON LIKE A BOSS.

Adds the method serializeObject to jQuery, to perform complex formserialization into JavaScript objects.

The current implementation relies in jQuery.serializeArray() to grab the formattributes and then create the object using the input name attributes.

This means it will serialize the inputs that are supported by.serializeArray(), that use the standard W3C rules for successful controlsto determine which inputs should be included; in particular:

  • The input cannot be disabled and must contain a name attribute.
  • No submit button value is serialized since the form is not submitted using a button.
  • Data from <input type='file'> inputs are not serialized.

Installation

option 1: NPM

option 2: Bower

option 3: Manual

Copy the dist/jquery.serialize-object.min.js to your project.

You can include the plugin in the HEAD element or at the bottom of your BODYtag. Wherever you choose to add it, it must be included after your jQuery.

2.0

Version 2.0 takes jquery-serialize-object into maturity. It is now backed by afull test suite so you can be confident that it will work in your web app.

Moving ahead, on top of core serialization, .serializeObject will supportcorrect serializaton for boolean and number values, resulting valid typesfor both cases.

Look forward to these >= 2.5.0

Update:>= 2.4.0 now serializes <input type='checkbox'> as a boolean. Seethe test for specific behavior.

API

Given a basic HTML form

.serializeObject — serializes the selected form into a JavaScript object

.serializeJSON — serializes the selected form into JSON

FormSerializer.patterns — modify the patterns used to match fieldnames

Many of you have requested to allow - in field names or use . to nest keys.You can now configure these to your heart's content.

Hyphen example

Dot-notation example

Validating and Key parsing

  • validate — only valid input names will be serialized; invalid nameswill be skipped

  • key — this pattern parses all 'keys' from the input name; You willwant to use /g as a modifier with this regexp.

Key styles

  • push — push a value to an array

  • fixed — add a value to an array at a specified index

  • named — adds a value to the specified key

Tests

If you have node.js installed, as a convenience, you can run

If you do not have node installed, simply

CoffeeScript

CoffeeScript has been dropped for >= 2.0.0. If members of the community wouldlike to support this, please feel free to add a CoffeeScript version.

If you'd like to use the the 1.0.0 version, it is still available here.

Contributing

See : CONTRIBUTING