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

时间:2017-07-25 14:04:26

标签: javascript jquery json

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

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

6 个答案:

答案 0 :(得分:3)

你可以用这个:

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

答案 1 :(得分:2)

您可以将<form>传递给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);
<form name='test'>
  <input type='text' name='login' value="a login">
  <input type='email' name='email' value="a email">
</form>

答案 2 :(得分:0)

如果你想要javascript对象:

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

和Json:

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

答案 3 :(得分:0)

如果你得到这个

[{"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] )

答案 4 :(得分:0)

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

&#13;
&#13;
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);
&#13;
<form name='test'>
  <input type='text' name='login'>
  <input type='email' name='email'>
</form>
&#13;
&#13;
&#13;

使用jQuery

&#13;
&#13;
var data = $('form :input').toArray().reduce( (a,b) => (a[b.name]=b.value,a),{})
var json = JSON.stringify(data,0,4);

console.log(data);
&#13;
<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>
&#13;
&#13;
&#13;

答案 5 :(得分:-2)

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

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