javascript - Convert nested form fields to JSON in Jquery -


trying post of form object json front end javacsript/jquery spring mvc backend. form data has string array , other string field, looks below

... var citylist = []; citylist.push("sf"); citylist.push("la"); document.forms["myform"]["dstcities"].value = citylist; document.forms["myform"]["dststate"].value = "ca"; ... 

below code converting json,

function convertformtojson(){     var jsonobject = {};     var array = $("myform").serializearray();      $.each(array, function() {         if (jsonobject[this.name] !== undefined) {             jsonobject[this.name].push(this.value || '');         } else {             jsonobject[this.name] = this.value || '';         }     });      jsonobject = json.stringify(jsonobject);     console.log("json: " + jsonobject);     return jsonobject; }; 

post call:

    $.ajax({         url: "xxx",         type: "post",         data: convertformtojson(),         contenttype: "application/json",         datatype: 'json',         ...    }); 

json output:

{"dstcities":"sf,la", "dststate":"ca"} 

but need like

[{"dstcities": ["sf", "la"], "dststate":"ca"}] 

you passing array value :

document.forms["myform"]["dstcities"].value = citylist; 

but browser using tostring() on , ends joined string "sf,la"

if intent pass string array can do:

document.forms["myform"]["dstcities"].value = json.stringify(citylist); 

no changes needed in convertformtojson way.


if cities need displayed comma separated values change

   if (jsonobject[this.name] !== undefined) {        jsonobject[this.name].push(this.value || '');    } else {        var value = this.value;        if (this.name === 'dstcities') {            value = value.split(',');        }        jsonobject[this.name] = value || '';    } 

Comments