Skip to content

Instantly share code, notes, and snippets.

@Onheiron
Created July 3, 2012 08:01
Show Gist options
  • Save Onheiron/3038382 to your computer and use it in GitHub Desktop.
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!
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;
}
@Onheiron
Copy link
Author

Onheiron commented Jul 3, 2012

How To:

  1. Write your HTML Form setting the name attribute for all the elements you want to put inside the JSON Object

  2. Call the function with your Form's root as "node" parameter :

    newJSON = fetch(formRoot);

  3. Here you go! newJSON now contains all the datas in your form as well as its structure! Youre now ready to send this baby over to your server!

@Onheiron
Copy link
Author

Onheiron commented Jul 7, 2012

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.

@Onheiron
Copy link
Author

Onheiron commented Jul 7, 2012

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