Convert FormData to JSON

You guessed it! This is how you convert FormData to json. Yippee!

Make a form

<form id="yowza">
  <input name="author" value="Tolkien" />

Capture the Submit

Now intercept that submit event:

function handleSubmit(evt) {
  const json = formatForm(
  // ...ajax submit, or whatever

  .addEventListener("submit", handleSubmit);

Convert Form Data

How do you get form data? Well, there's a nice API called FormData. Let's instantiate that, pass our form to it, then call FormData.entries() to get JSON out:

function formatForm(form) {
  return Array.from(new FormData(form).entries()).reduce((acc, entry) => {
    return {
      [entry[0]]: entry[1]
  }, {})

Yielding something like:

{ name: 'Tolkien' }

JSON!, into the wild, blue yonder.