Serialize Form to JSON

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           if (!o[this.name].push) {
               o[this.name] = [o[this.name]];
           }
           o[this.name].push(this.value || '');
       } else {
           o[this.name] = this.value || '';
       }
   });
   return o;
};

Comments

  1. User Avatar
    Luca
    Permalink to comment#

    This is not at all ‘javascript’. This is a jQuery snippet.

    • User Avatar
      GURU
      Permalink to comment#

      This is Javascript, as jQuery is a framework using Javascript as the language!

      Fool’s like you shouldn’t be allowed to post comments!

    • User Avatar
      Yann
      Permalink to comment#

      Waoww, thanks Luca for the very usefull comment.
      By the way, as you seem very keen to point out not relevant details
      then you should write JavaScript correctly.

      Tghe snippet above will not handle nested form objects correctly,
      the follwing jQuery would work it out better:

      (function(jQuery){

      jQuery.fn.MytoJson = function(options) {
      
          options = jQuery.extend({}, options);
      
          var self = this,
              json = {},
              push_counters = {},
              patterns = {
                  "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
                  "key":      /[a-zA-Z0-9_]+|(?=\[\])/g,
                  "push":     /^$/,
                  "fixed":    /^\d+$/,
                  "named":    /^[a-zA-Z0-9_]+$/
              };
      
      
          this.build = function(base, key, value){
              base[key] = value;
              return base;
          };
      
          this.push_counter = function(key){
              if(push_counters[key] === undefined){
                  push_counters[key] = 0;
              }
              return push_counters[key]++;
          };
      
          jQuery.each(jQuery(this).serializeArray(), function(){
      
              // skip invalid keys
              if(!patterns.validate.test(this.name)){
                  return;
              }
      
              var k,
                  keys = this.name.match(patterns.key),
                  merge = this.value,
                  reverse_key = this.name;
      
              while((k = keys.pop()) !== undefined){
      
                  // adjust reverse_key
                  reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
      
                  // push
                  if(k.match(patterns.push)){
                      merge = self.build([], self.push_counter(reverse_key), merge);
                  }
      
                  // fixed
                  else if(k.match(patterns.fixed)){
                      merge = self.build([], k, merge);
                  }
      
                  // named
                  else if(k.match(patterns.named)){
                      merge = self.build({}, k, merge);
                  }
              }
      
              json = jQuery.extend(true, json, merge);
          });
      
      
          return json;
      }
      

      })(jQuery);

    • User Avatar
      Jona
      Permalink to comment#

      Thank you very much yann. It works with complex arrays in form.

    • User Avatar
      Tom
      Permalink to comment#

      Bravo, Luca. Javascript is the language, jQuery is a third-party software package written for/in javascript. The point is relevant since there is a distinction.

  2. User Avatar
    Chris Coyier
    Permalink to comment#

    Moved.

  3. User Avatar
    Craig
    Permalink to comment#

    I’m very new to JQuery, and this is probably a silly request, but could you provide an example of usage? Is it something like $("#myForm").serializeObject?

    • User Avatar
      Virgil Spruit
      Permalink to comment#

      Don’t forget to use the name attribute at your inputs.

    • User Avatar
      ghanshyam
      Permalink to comment#

      use this
      var myformdata = $(“#myForm”).serializeObject();

  4. User Avatar
    game
    Permalink to comment#

    I’m still not quite understand.

  5. User Avatar
    Ignacio

    Hi, im using a flash gallery, and i have to implement it into a web for a new customer.

    The gallery generates a JSON file as follows:
    {"gallery":{"items":[{"description":"","link":"","thumb":"gallery/images/t2.jpg","target":"","source":"gallery/images/1.jpg"},
    {"description":"","link":"","thumb":"gallery/images/t2.jpg","target":"","source":"gallery/images/2.jpg"},
    {"description":"","link":"","thumb":"gallery/images/t3.jpg","target":"","source":"gallery/images/3.jpg"},
    {"description":"","link":"","thumb":"gallery/images/t4.jpg","target":"","source":"gallery/images/4.jpg"},
    {"description":"","link":"","thumb":"gallery/images/t5.jpg","target":"","source":"gallery/images/5.jpg"}],
    "settings":{"background":{"bgColor":16777215,"transparentBG":true},"image":{"scaleMode":"fill","cornerRadius":10,"transitionDuration":1,"align":"center","transitionEffect":"fit","useShadow":true},"caption":{"position":"bottom","bgColor":0,"color":16777215,"visibleMode":"onRollOver","bgAlpha":30,"fontName":"Arial","fontSize":11},"preview":{"usePreview":true,"alpha":100,"outlineColor":0,"height":100,"cornerRadius":10,"width":200,"useShadow":true},"slideshow":{"start":false,"delay":2.5,"loop":true,"stopAutoOnClick":true},"dimensions":{"height":385,"width":470},"thumbBar":{"scrollSpeed":10,"position":"bottom","useThumbBar":true},"preloader":{"alpha":80,"usePreloader":true},"thumbnail":{"cornerRadius":0,"useShadow":true,"outlineColor":3355443,"outlineColorOnRollOver":6710886,"height":45,"alpha":70,"width":60,"outlineColorOnClick":10066329},"buttons":{"position":"right","fullScreenButton":true,"navigationButtons":true,"slideshowButton":true}}},"galleryName":"Art Gallery"}

    Can anyone show me the code to insert values from a form in html??

    Thanks in advance

  6. User Avatar
    jeremy
    Permalink to comment#

    @Ignacio – You’ll need to loop through the json object created from this function and just create another variable that you copy items too.

  7. User Avatar
    Dema
    Permalink to comment#

    HI everyone,
    I would like to know if there is in jquery a form reservation for input and output date, I would like to find some tuto .
    I want to use for booking rooms

    thanks a lot

  8. User Avatar
    Idham
    Permalink to comment#

    This snippet useful until now.

  9. User Avatar
    Marcio
    Permalink to comment#

    My result when a do alert it repeat de values in each json itens

  10. User Avatar
    MarioMC

    Dude, thank you for this. I started here, then got sidetracked by some of the links in the comments, and after a roundabout trip all across the internet found my way back, to this, the only actual working solution.

    Thanks so much, appreciate it!

  11. User Avatar
    Jesse Donat
    Permalink to comment#

    Doesn’t appear to work on fields named for instance start[125]

    I get back

    {
    "start[125]":""
    }

    rather than the desired

    {
    "start":{"125":""}
    }
  12. User Avatar
    Posni
    Permalink to comment#

    This seems to be copied (judging from dates) from Stackoverflow: http://stackoverflow.com/questions/1184624/convert-form-data-to-js-object-with-jquery

    • User Avatar
      DMC
      Permalink to comment#

      I think you’re missing the point of sharing snippets of code…

  13. User Avatar
    nicolas
    Permalink to comment#

    confused about this part
    if (!o[this.name].push)

    I am not very good at this yet, sorry~

  14. User Avatar
    Assis
    Permalink to comment#

    People should always be nice to each other. Rude people shouldn’t be allowed to post comments.

  15. User Avatar
    Corey Rothwell
    Permalink to comment#

    Works awesome for simple forms! thanks!

  16. User Avatar
    rajesh
    Permalink to comment#

    I need, make a new json format from json Object.

    Here I have following json object result:

    [
    {
    “Location.Country”: “India”,
    “Location.City”: “Chennai”,
    “Location.Office”: “Shriram IT Gateway”,
    “countstar”: 243
    },
    {
    “Location.Country”: “India”,
    “Location.City”: “Chennai”,
    “Location.Office”: “MEPZ”,
    “countstar”: 173
    },
    {
    “Location.Country”: “Australia”,
    “Location.City”: “Sydney”,
    “Location.Office”: “CSS Australia”,
    “countstar”: 1
    },
    {
    “Location.Country”: “India”,
    “Location.City”: “Bangalore”,
    “Location.Office”: “Glow Network”,
    “countstar”: 9
    },
    {
    “Location.Country”: “United States”,
    “Location.City”: “Richardson”,
    “Location.Office”: “Dallas”,
    “countstar”: 17
    },
    {
    “Location.Country”: “India”,
    “Location.City”: “Chennai”,
    “Location.Office”: “West Wing”,
    “countstar”: 174
    },
    {
    “Location.Country”: “United States”,
    “Location.City”: “Utah”,
    “Location.Office”: “Utah”,
    “countstar”: 29
    }
    ]

    Convert New Format

    {
    “name”:”Locations”,
    “children”:[
    {
    “name”:”india”,
    “children”:[
    {
    “name”:”Chennai”,
    “children”:[
    {
    “name”:”Shriram IT Gateway”,
    “size”:1541
    },
    {
    “name”:”Mainwing”,
    “size”:1170
    },
    {
    “name”:”Ambit”,
    “size”:4626
    },
    {
    “name”:”Mepz”,
    “size”:1296
    }
    ]
    },
    {
    “name”:”Bangalore”,
    “children”:[
    {
    “name”:”ITPL Bangalore”,
    “size”:5
    },
    {
    “name”:”Banaglore”,
    “size”:241
    }
    ]
    },
    {
    “name”:”Hyderabad”,
    “size”:87
    },
    {
    “name”:”Coimbatore”,
    “size”:29
    },
    {
    “name”:”Perungalathur”,
    “size”:67
    },
    {
    “name”:”Glow Network”,
    “size”:122
    }
    ]
    },
    {
    “name”:”United States”,
    “children”:[
    {
    “name”:”Dallas”,
    “size”:299
    },
    {
    “name”:”Texas”,
    “size”:8
    },
    {
    “name”:”Newyork”,
    “size”:49
    },
    {
    “name”:”Boston”,
    “size”:10
    },
    {
    “name”:”Utah”,
    “size”:399
    },
    {
    “name”:”Washington”,
    “size”:2
    },
    {
    “name”:”Sanjose”,
    “size”:97
    }
    ]
    }
    }

  17. User Avatar
    rajesh
    Permalink to comment#

    please help me?

  18. User Avatar
    Mario
    Permalink to comment#

    This jQuery plugin handles Form to JSON both to simple and complex conversions:
    https://github.com/marioizquierdo/jquery.serializeJSON

    Usage: $(“form”).serializeJSON()

    • User Avatar
      Andrew
      Permalink to comment#

      This is a good plugin and is very flexible (such as ability to include unchecked checkboxes), however when parsing select multiples, if one item is selected it won’t add it to the array but set as simply a value, with many REST endpoints I’ve worked with it expects an array in the JSON, regardless how many elements there are.
      This goes back to the serializeArray plugin (which I assume the plugin is based on) which doesn’t keep track of whether that input element is a select multiple and simply spits out all the key values for each selected option, then when you want to create the JSON output unless you check once more the corresponding form input while iterating there is no way to find out if it’s a select multiple and that it needs to be in a array. This is simply solved but seems like serializeArray is kind of pointless as a starting point for more complex cases.

  19. User Avatar
    manoj

    is it possible to create a form with css styles in json

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag