将表单数据转换为JSON字符串

如果我使用JSON.serialize($(form)).serializeArray();
我得到[{"name":"login","value":"a value"},{"name":"email","value":"a email"}]而我需要{"login":"a login","email":"a email"} 。 怎么做??

您可以将

传递给FormData() ,迭代FormData实例的键值对,将每个键和值设置为对象属性和值

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

你可以用这个:

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

如果你想要javascript对象:

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

而Json:

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

如果你得到这个

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

你只需要

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

只需通过索引调用变量即可

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

另一种方法是使用普通的js和form.elements作为Array.reduce的参数

 var d = [].reduce.call(document.forms['test'].elements,(a,b)=>(a[b.name]=b.value,a),{}); var j = JSON.stringify(data, 0, 4); console.log(j); 
 

利用.serializeArray()的真正快速解决方案是:

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