Skip to content

Instantly share code, notes, and snippets.

@DavidCramer
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidCramer/086b6e59dd4c05385365 to your computer and use it in GitHub Desktop.
Save DavidCramer/086b6e59dd4c05385365 to your computer and use it in GitHub Desktop.
form to json with nested fields
$.fn.formJSON = function(){
var fields = $(this).serializeArray(),
json = {},
arraynames = {};
for( var v = 0; v < fields.length; v++){
var field = fields[v],
name = field.name.replace(/\]/gi,'').split('['),
value = field.value,
lineconf = {};
for(var i = name.length-1; i >= 0; i--){
var nestname = name[i];
if(nestname.length === 0){
if( typeof arraynames[name[i-1]] === 'undefined'){
arraynames[name[i-1]] = 0;
}else{
arraynames[name[i-1]] += 1;
}
nestname = arraynames[name[i-1]];
}
if(i === name.length-1){
if( value === 'true' ){
value = true;
}else if( value === 'false' ){
value = false;
}else if( !isNaN( parseFloat( value ) ) ){
value = parseFloat( value );
}
lineconf[nestname] = value;
}else{
var newobj = lineconf;
lineconf = {};
lineconf[nestname] = newobj;
}
}
$.extend(true, json, lineconf);
};
return json;
}
@DavidCramer
Copy link
Author

Converts a form to JSON.
See Example
Works with nested names name="data[value][]".
It's not perfect since array fields [] becomes an object {"0","value"} rather than["value"]`, but at 38 lines of code, it's pretty effective and fast.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment