Created
July 3, 2012 08:01
-
-
Save Onheiron/3038382 to your computer and use it in GitHub Desktop.
Gets datas form your HTML form and generates a JSON Object out of it!
This file contains hidden or 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
function toJSON(node){ | |
if(!$(node).children().length) return $(node).val(); | |
var json = new Object(); | |
$(node).children('[name]').each(function(){ | |
if($(this).siblings("[name="+$(this).attr('name')+"]").length){ | |
if(!json[$(this).attr('name')]) json[$(this).attr('name')] = []; | |
json[$(this).attr('name')].push(toJSON(this)); | |
}else if($(this).children('[name]').length){ | |
json[$(this).attr('name')] = toJSON(this); | |
}else{ | |
json[$(this).attr('name')] = $(this).val(); | |
} | |
}); | |
return json; | |
} |
Here's one line compressed string:
function toJSON(a){if(!$(a).children().length)return $(a).val();var b=new Object;$(a).children("[name]").each(function(){e=$(this);c=e.attr("name");if(e.siblings("[name="+c+"]").length){if(!b[c])b[c]=[];b[c].push(toJSON(this))}else if(e.children("[name]").length){b[c]=toJSON(this)}else{b[c]=e.val()}});return b}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fixed code for better optimization. Iteration is now on children("[name]") so that only children with name attribute are iterated and the "has name" conditional can be deleted.