How to Convert HTML Form Data to a JSON String in JavaScript?

Using JavaScript, you can choose different ways to convert HTML form values to a JSON string depending on the following:

Form Without Elements That Allow Multiple Selections

If your HTML form does not have elements that allow multiple selections (such as <select multiple>, checkboxes that have the same name, etc.), then you can simply do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form:

<form id="myForm">
  <input type="text" name="name" value="John" />
  <input type="email" name="email" value="[email protected]" />
  <input type="number" name="age" value="29" />
  <button type="submit">Submit</button>
</form>

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

// ES10+
const form = document.getElementById('myForm');

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const jsonObject = Object.fromEntries(formData);
  // 3: convert form data object to a JSON string
  const jsonString = JSON.stringify(jsonObject);

  console.log(jsonString); // '{"name":"John","email":"[email protected]","age":"30"}'
});

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

const form = document.getElementById('myForm');

function formDataToObject(formData) {
  const jsonObject = {};

  for (const [key, value] of formData.entries()) {
    jsonObject[key] = value;
  }

  return jsonObject;
};

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const jsonObject = formDataToObject(formData);
  // 3: convert form data object to a JSON string
  const jsonString = JSON.stringify(jsonObject);

  console.log(jsonString); // '{"name":"John","email":"[email protected]","age":"30"}'
});

Form With Elements That Allow Multiple Selections

If your HTML form does have elements that allow multiple selections (such as <select multiple>, checkboxes that have the same name, etc.), then you can do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object — if an element has multiple values, store an array of all the values. Otherwise, store the single value;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form that has a multi-select and checkboxes with the same name attribute:

<form id="myForm">
  <input type="checkbox" name="filters[]" value="hotels" checked /> Hotel
  <input type="checkbox" name="filters[]" value="apartments" checked /> Apartments
  <select name="preference" multiple>
    <option value="single" selected>Single Room</option>
    <option value="double" selected>Double Room</option>
    <option value="king">King Size Room</option>
  </select>
  <button type="submit">Submit</button>
</form>

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

// ES10+
const form = document.getElementById('myForm');

function formDataToObject(formData) {
  const normalizeValues = (values) => (values.length > 1) ? values : values[0];
  const formElemKeys = Array.from(formData.keys());

  return Object.fromEntries(
    formElemKeys.map(key => [key, normalizeValues(formData.getAll(key))])
  );
}

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const jsonObject = formDataToObject(formData);
  // 3: convert form data object to a JSON string
  const jsonString = JSON.stringify(jsonObject);

  console.log(jsonString); // '{"filters[]":["hotels","apartments"],"preference":["single","double"]}'
});

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

// ES5+
const form = document.getElementById('myForm');

function formDataToObject(formData) {
  const normalizeValues = (values) => (values.length > 1) ? values : values[0];
  const object = {};

  for (const [key, value] of formData.entries()) {
    object[key] = normalizeValues(formData.getAll(key));
  }

  return object;
};

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const jsonObject = formDataToObject(formData);
  // 3: convert form data object to a JSON string
  const jsonString = JSON.stringify(jsonObject);

  console.log(jsonString); // '{"filters[]":["hotels","apartments"],"preference":["single","double"]}'
});

In either of the examples, the formDataToObject() function processes each form element and returns either a single value or an array of values, depending on whether the element has multiple values or not. This value is then added to its corresponding form element key in the resulting object.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.