4

I have the following form ...

<form id="my-form">

  <fieldset name="address">
    <input name="streetAddress" type="text" placeholder="Street Address"><br>
    <input name="city"          type="text" placeholder="City"><p>,</p>
    <input name="state"         type="text" placeholder="State">
    <input name="zipCode"       type="text" placeholder="Zip Code">
  </fieldset>

  <fieldset name="dimensions">
    <input name="length" type="text" placeholder="length">
    <input name="width"  type="text" placeholder="width">
    <input name="height" type="text" placeholder="height">
  </fieldset>

</form>

I need to serialize it into JSON with JS, but I need to have the address's fields warped in an address object, and the dimensions's fields warped in a dimensions object.

Something like this ...

{
    'address':{'streetAddress':'111 Candy Ln', 'city':'Los Angeles', ...}, 
    'dimensions':{...}
}

How do you do this cleanly, idealy without having to write my own function for doing this? I have of course seen scripts to serialize, but nothing that will do embedded objects.

6
  • Why do you need to serialize it with JSON, what are you doing with it? Commented Jun 22, 2013 at 20:46
  • Yes, it's a web-application with a REST GAE back-end. I have already settled on JSON, everything is JSON. Thanks. Commented Jun 22, 2013 at 20:49
  • Are you going to send it via Ajax or Json in a form field? Commented Jun 22, 2013 at 21:10
  • Solved your problem, below....take a look :) Commented Jun 22, 2013 at 21:15
  • Thanks Aiias for the corrected the "[...]" to "{...}, not sure what was going though my head. Commented Jun 22, 2013 at 21:27

2 Answers 2

2

Have you tried putting all the fields into arrays?

<fieldset name="address">
<input name="address[streetAddress]" type="text" placeholder="Street Address"><br>
<input name="address[city]" type="text" placeholder="City"><p>,</p>
<input name="address[state]" type="text" placeholder="State">
<input name="address[zipCode]" type="text" placeholder="Zip Code">
</fieldset>

Heres an example, using the serializeObject plugin

Just include that script and you can convert any form into a multi layered JSON object.

DEMO HERE

Using this plugin...more info here Convert form data to JavaScript object with jQuery

(function($){
$.fn.serializeObject = function(){

    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]++;
    };

    $.each($(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 = $.extend(true, json, merge);
    });

    return json;
};
})(jQuery);
Sign up to request clarification or add additional context in comments.

Comments

1

I have two solutions for this:

  1. Name the fields after the fieldsets (like the proposal above): address[street], address[zipcode], etc.
  2. Give the fieldsets some unique id's.

In both cases I suggest you using this library I made: https://github.com/serbanghita/formToObject

Call it like this:

Case 1: var myFormObj = new formToObject('myFormId');

Case 2: var myFormObj = new formToObject('myFieldsetId');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.