Last active
August 29, 2015 14:08
-
-
Save DavidCramer/086b6e59dd4c05385365 to your computer and use it in GitHub Desktop.
form to json with nested fields
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
$.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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.