dippy tippy
dippy tippy

Reputation: 527

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??

Upvotes: 4

Views: 8735

Answers (6)

adeneo
adeneo

Reputation: 318182

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>

Upvotes: 1

ema
ema

Reputation: 5773

You could use this:

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

Upvotes: 4

Marcogomesr
Marcogomesr

Reputation: 2672

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

Upvotes: 0

Lucas
Lucas

Reputation: 1311

If you want javascript object:

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

And the Json:

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

Upvotes: 0

guest271314
guest271314

Reputation: 1

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>

Upvotes: 4

victor
victor

Reputation: 812

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

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

Upvotes: -2

Related Questions