Categories
JavaScript Answers

How to Convert JavaScript FormData to Object to JSON?

Spread the love

Sometimes, we want to convert the JavaScript form data object to JSON.

In this article, we’ll look at how to convert the JavaScript form data object to JSON.

Convert JavaScript FormData to Object to JSON

We can convert JavaScript form data objects to JSON strings easily with the Object.fromEntries and the JSON.strinnfiyt methods.

Object.fromEntries lets us convert an array of key-value pair arrays to an object.

And JSON.stringify lets us convert an object to a JSON string with the JSON object.

For instance, we can create a form:

<form>  
  Email <input name='email'>  
  Password <input name='password' type='password'>  
  <input type='submit'>  
</form>

Then we can listen to the submit event on the form with JavaScript:

const form = document.querySelector('form')  
form.addEventListener('submit', (e) => {  
  e.preventDefault()  
  const formData = new FormData(e.target)  
  const json = JSON.stringify(Object.fromEntries(formData));  
  console.log(json)  
})

We call addEventListener on the form to listen to the submit event.

In the submit event callback, we call e.preventDefault to prevent the default server-side submit behavior.

Then we create a form data object from the form with the FormData constructor.

e.target has the form element.

Next, we call Object.fromEntries to convert the formData into an object with the keys being the value of the name attribute of each input, and the value being the inputted value of each field.

And finally, we call JSON.stringify to convert the object into a JSON string with the object.

Therefore, json is something like:

{"email":"abc","password":"abc"}

if we typed in 'abc' into each field.

Conclusion

We can convert JavaScript form data objects to JSON strings easily with the Object.fromEntries and the JSON.strinnfiyt methods.

Object.fromEntries lets us convert an array of key-value pair arrays to an object.

And JSON.stringify lets us convert an object to a JSON string with the JSON object.

One reply on “How to Convert JavaScript FormData to Object to JSON?”

I don’t think Object.fromEntries works properly with checkboxes or multi-selects, where the fields have the same name.

Leave a Reply

Your email address will not be published. Required fields are marked *