How to turn an HTML form into JSON

Saturday, Feb 24 2018 in javascript

To send data from an HTML form to a JSON API, you can extract all the form data in one go with form-serialize.

form-serialize exposes a single function. Passing the form DOM node to it and { hash: true } as the second argument returns a JavaScript object with the form data:

import serialize from 'form-serialize';

const formData = serialize(formNode, { hash: true });

The object values are the form field values and the keys are the corresponding name attributes. For example, calling serialize() on this form:

  <input type="text" name="firstName"/>
  <select name="birthYear">

gives you this object:

  firstName: '...', /* input value */
  birthYear: '...' /* select value */

If your API expects different keys, create a new object from the one that serialize() returns:

const apiData = { name: formData.firstName, year: formData.birthYear };

Then turn the object into a JSON string:

const json = JSON.stringify(apiData);

Moving data from the form into a JavaScript object and into JSON takes two lines of code.

Want learn into React?

Try React for Real.