34

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:

Screen capture

I have tried doing this

var formData = JSON.parse($("#floorplan-form").serializeArray());

But I get this error:

Uncaught SyntaxError: Unexpected token o 

7 Answers 7

47

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
Sign up to request clarification or add additional context in comments.

3 Comments

Does one need to add a reference to an external file? is that JSON class included in jQuery ?
Lol kids these days with their fancy jQuery... the JSON object is part of Javascript's built-in objects. Has nothing to do with jQuery.
To modify the formData of jquery file upload, I can only make it via third method, thanks
24

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);

1 Comment

This is the right answer if you have a serialized string and want to convert it back to an object. It would be helpful to have a little more explanation rather than a code only answer.
11
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);

1 Comment

You can also use jQuery.each in place of jQuery.map
3

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);

Comments

2

You can use: jquery.serializeToJSON - https://github.com/raphaelm22/jquery.serializeToJSON Its is prepared to work with forms ASP MVC

Comments

2

A modern interpretation. babel stage-2 preset is required to compile the object spread operator

// serializeToJSON :: String -> JSON
const serializeToJSON = str => 
  str.split('&')
    .map(x => x.split('='))
    .reduce((acc, [key, value]) => ({
      ...acc,
      [key]: isNaN(value) ? value : Number(value)
    }), {})

console.log(
  serializeToJSON('foo=1&bar=2&baz=three')
)

Comments

2

You could do the following to convert a serialize data to json object, this would take the array of fields in form and iterate over it asigning the keys and values to a new object.

let uncleandata = $(this).serializeArray();
let data = {};
uncleandata.forEach(item=>{
  data[item.name] = item.value;
});
console.log(data);

1 Comment

The best answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.