简体   繁体   中英

Covert form data to JSON string

<form name = 'test' >
    <input type='text' name = 'login'>
    <input type='email' name = 'email'>
</form>

If I use JSON.serialize($(form)).serializeArray();
I get [{"name":"login","value":"a value"},{"name":"email","value":"a email"}] while I need {"login":"a login","email":"a email"} . How to do that??

You could use this:

JSON.stringify($(form).serializeArray().reduce((acc, f) => {
  acc[f.name] = f.value
  return acc
}, {})

You can pass the <form> to FormData() , iterate key, value pairs of FormData instance, set each key and value to an object property and value

 let form = document.forms["test"]; let fd = new FormData(form); let data = {}; for (let [key, prop] of fd) { data[key] = prop; } data = JSON.stringify(data, null, 2); console.log(data); 
 <form name='test'> <input type='text' name='login' value="a login"> <input type='email' name='email' value="a email"> </form> 

Another way to do this, using plain js and form.elements as an argument to Array.reduce

 var d = [].reduce.call(document.forms['test'].elements,(a,b)=>(a[b.name]=b.value,a),{}); var j = JSON.stringify(d, 0, 4); console.log(j); 
 <form name='test'> <input type='text' name='login'> <input type='email' name='email'> </form> 

Using jQuery

 var data = $('form :input').toArray().reduce( (a,b) => (a[b.name]=b.value,a),{}) var json = JSON.stringify(data,0,4); console.log(data); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name='test'> <input type='text' name='login'> <input type='email' name='email'> </form> 

If you want javascript object:

 let dest = {};
 $( form )
     .serializeArray()
     .map( input => dest[ input.name ] = input.value );

And the Json:

 console.log( JSON.stringify( dest ) );

if you get this

[{"name":"login","value":"a value"},{"name":"email","value":"a email"}];

and you need just

{"name":"login","value":"a value"}

just call the variable by their index

 var data = [{"name":"login","value":"a value"},{"name":"email","value":"a email"}]; console.log( data[0] ) 

real quick solution that utilizes .serializeArray() would be:

var objArr = JSON.serialize($(form)).serializeArray();
var obj = objArr.pop();
var strJson = JSON.serialize(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM