Skip to content

Instantly share code, notes, and snippets.

@cmilfont
Created November 2, 2012 00:39
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cmilfont/3997874 to your computer and use it in GitHub Desktop.
(function($){
var merge = function(merged, source){
for(var property in source) {
if( typeof source[property] === "object" &&
typeof merged[property] !== "undefined") {
merge(merged[property], source[property]);
} else {
merged[property] = source[property];
}
}
return merged;
};
var build = function(name, value){
return (function gerarJSON(json, name, value){
var hierarquia = name.split(".");
var propriedade = hierarquia.shift();
json[propriedade] = (hierarquia.length > 0)?
gerarJSON({}, hierarquia.join(".", value)):value;
return json;
})({}, name, value);
}
$.fn.extend({
getJSON: function(){
var json = {};
$(this).find("input,select,textarea")
.each(function(index, input){
var parcial = build( $(input).attr("name"), $(input).val());
merge(json, parcial);
});
return json;
}
});
})(jQuery);
$("form").getJSON()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment