Last active
December 26, 2015 09:09
-
-
Save dubilla/7127199 to your computer and use it in GitHub Desktop.
Serializing forms to JSON via http://css-tricks.com/snippets/jquery/serialize-form-to-json/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/hattip http://css-tricks.com/snippets/jquery/serialize-form-to-json/#comment-210474