Converting serialized form's data to json object
103,987
Solution 1
Change your statement
var formData = JSON.parse($("#floorplan-form").serializeArray());
with
var formData = JSON.stringify(jQuery('#frm').serializeArray()); // store json string
or
var formData = JSON.parse(JSON.stringify(jQuery('#frm').serializeArray())) // store json object
Solution 2
Use the code below!!!
var data = $("form").serialize().split("&");
console.log(data);
var obj={};
for(var key in data)
{
console.log(data[key]);
obj[data[key].split("=")[0]] = data[key].split("=")[1];
}
console.log(obj);
Solution 3
function jQFormSerializeArrToJson(formSerializeArr){
var jsonObj = {};
jQuery.map( formSerializeArr, function( n, i ) {
jsonObj[n.name] = n.value;
});
return jsonObj;
}
Use this function. This will work only with jquery.
var serializedArr = $("#floorplan-form").serializeArray();
var properJsonObj = jQFormSerializeArrToJson(serializedArr);
Solution 4
You can use this for make a json with all fields of form.
Jquery example:
$('form').serializeArray().reduce(function(accumulator,currentValue, currentIndex){
if(currentIndex === 1){
var json = {};
json[accumulator.name] = accumulator.value;
return json;
}
accumulator[currentValue.name] = currentValue.value;
return accumulator;
});
Pure JavaScript with FormData:
var formdata = new FormData(document.querySelector('form'));
var getJsonFromFormData = (formData) => {
var json = {};
for (item of formData.keys()){
json[item] = formData.get(item);
}
return json;
}
var json = getJsdonFromFormData(formdata);
Solution 5
You can use: jquery.serializeToJSON - https://github.com/raphaelm22/jquery.serializeToJSON Its is prepared to work with forms ASP MVC
Comments
-
Null Reference over 2 years
I have a cshtml like the following
@using (Html.BeginForm("Save", "Plans", FormMethod.Post, new { @class = "form-horizontal", id = "floorplan-form" })) { @Html.TextBoxFor(m => m.FloorPlan.Name, new { placeholder = "Enter text", @class = "form-control" }) @Html.DropDownListFor(m => m.FloorPlan.GroupId, new SelectList(Model.FloorPlanGroups, "Id", "Name")) }
In my javascript(in a separate javascript file), I'm trying to serialize this form and convert it into a JSON object.
var formData = $("#floorplan-form").serialize(); console.info(formData);
prints out
FloorPlan.Name=Test&FloorPlan.GroupId=15
And
var formData = $("#floorplan-form").serializeArray(); console.info(formData);
gives me:
I have tried doing this
var formData = JSON.parse($("#floorplan-form").serializeArray());
But I get this error:
Uncaught SyntaxError: Unexpected token o