How to easily convert HTML Form to JSON
Tags: webdev, javascript, html, form
Published: 2020-12-21 13:56:46

---
title: How to easily convert HTML Form to JSON
published: true
description: Convert HTML Forms to JSON using zero dependencies with the power of the web platform!
tags: webdev, JavaScript, html, form
series: Web Dev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/her8yp0wvrwft3m3iin3.png
canonical_url: https://jordanfinners.dev/blogs/how-to-easily-convert-html-form-to-json
---

# Contents 
1. [Intro](#intro)
2. [Form Data](#form-data)
3. [Gotcha's](#gotcha)
4. [Examples](#examples)
5. [Summary](#summary)

# Intro <a name="intro"></a>

I have a love, but sometimes hate, relationship with HTML Forms. HTML Forms are absolutely brilliant for out of the box validation, accessibility and usability. But they can be a pain to style!
Nevertheless, HTML Forms give you massive amounts of functionality with zero dependencies. 

If you are anything like me, you prefer your API to be JSON based. Making it easier and more consistent to deal with requests and responses on the backend.
You _could_ add a middleware to your API endpoint that's going to handle your Form UI but why make that endpoint different from the rest?

What if you could send your Form data off in JSON format and handle it like all your other endpoints. Now you can!

TLDR; Skip to the [examples](#examples)

# Form Data <a name="form-data"></a>

Introducing [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData), this is a really nice Web API for manipulating data in HTML Forms.

This allows us to easily convert a HTML Form to JSON using the following.

1. Grab the form element from the DOM.
```javascript
const formElement = document.querySelector('form')
```
2. Pass the form to the following function
```javascript
/**
 * Creates a json object including fields in the form
 *
 * @param {HTMLElement} form The form element to convert
 * @return {Object} The form data
 */
const getFormJSON = (form) => {
  const data = new FormData(form);
  return Array.from(data.keys()).reduce((result, key) => {
    result[key] = data.get(key);
    return result;
  }, {});
};
```
3. Action the JSON Object result, however you want to handle the data from the form! Send it off with [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) for example.

# Gotcha's <a name="gotcha"></a>

As with everything these are a few gotchas to look out for!

## Checkbox's

If ticked your checkbox's will appear in the result as 'on'. Probably not the boolean you want.
For example, if you've got this input in your form, which the user has checked.
```html
<input name="isOpen" type="checkbox" checked />
```
It would produce, using the function above:
```json
{
  "isOpen": "on"
}
```
You will probably want to check for the property and if it equals 'on' and convert it to a boolean.

## File Uploads

This one really caught me out, if you've got a file input which accepts multiple files, like so:
```html
<input name="uploads" type="file" multiple />
```
If one file is uploaded you will get a [File](https://developer.mozilla.org/en-US/docs/Web/API/File) object.
But if you have multiple files uploaded, you will actually get a list of them.

Fortunately, there is a really simple fix for this to consistently provide you with a list of files.
Grab the files from the result and process them like so:
```javascript
[files].flat().filter((file) => !!file.name)
```
This will consistently give you a list of files, handling if only a single file is uploaded, no file is uploaded or multiples are uploaded.

This also means you can do more client side checks on file sizes and limits for example as well.

## Inputs with the same name

Let's say you've got a list of possible tags and a user can tick the ones that apply, perhaps which programming languagues they know, like so:
```html
<input name="tags" type="checkbox" value="javascript" />
<input name="tags" type="checkbox" value="python" />
```
With the current solution, you would only get the last selected checkbox as the keys would be overridden in the reduce. However there is a simple fix for this as well.

We check to see if the key (the name attribute on the input) already exists in the result, if it does then use a [getAll](https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll) method which will get a list of results.
```javascript
/**
 * Creates a json object including fields in the form
 *
 * @param {HTMLElement} form The form element to convert
 * @return {Object} The form data
 */
const getFormJSON = (form) => {
  const data = new FormData(form);
  return Array.from(data.keys()).reduce((result, key) => {
    if (result[key]) {
      result[key] = data.getAll(key)
      return result
    }
    result[key] = data.get(key);
    return result;
  }, {});
};
```
Similarly, to the file upload before, you'll want to handle only one being ticked, no being ticked or multiple, with something like this.
```javascript
[result.tags || []].flat();
```

# Examples <a name="examples"></a>

Shut up and show me the code.

1. [Interactive](#examples/interactive)
2. [Simple](#examples/simple)
3. [Full](#examples/full)
4. [Bonus: Example Test](#examples/test)

<a name="examples/interactive"></a>
{% jsfiddle https://jsfiddle.net/Lmg1f3tu/ result,html,css,js %} 

## Simple Example <a name="examples/simple"></a>
```html
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
</head>

<body>
  <form name="forms" id="forms">
    <label>Whats your username?
      <input name="username" type="text" />
    </label>
    <label>How many years have you been a developer?
      <input name="age" type="number" />
    </label>
    <button type="submit">Submit</button>
  </form>

  <script>
    // get the form element from dom
    const formElement = document.querySelector('form#forms')

    // convert the form to JSON
    const getFormJSON = (form) => {
      const data = new FormData(form);
      return Array.from(data.keys()).reduce((result, key) => {
        result[key] = data.get(key);
        return result;
      }, {});
    };

    // handle the form submission event, prevent default form behaviour, check validity, convert form to JSON
    const handler = (event) => {
      event.preventDefault();
      const valid = formElement.reportValidity();
      if (valid) {
        const result = getFormJSON(formElement);
        console.log(result)
      }
    }

    formElement.addEventListener("submit", handler)
  </script>
</body>
```

## Full Example <a name="examples/full"></a>
```html
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
</head>

<body>
  <form name="forms" id="forms">
    <label>Whats your username?
      <input name="username" type="text" />
    </label>
    <label>How many years have you been a developer?
      <input name="age" type="number" />
    </label>

    <label>Upload images
      <input name="images" type="file" accept="image/png, image/jpeg" multiple />
    </label>

    <label>Do you know javascript?
      <input name="languages" type="checkbox" value="javascript" />
    </label>
    <label>Do you know python?
      <input name="languages" type="checkbox" value="python" />
    </label>

    <label>Enjoyed this blog?
      <input name="isHappyReader" type="checkbox" />
    </label>

    <button type="submit">Submit</button>
  </form>

  <script>
    // get the form element from dom
    const formElement = document.querySelector('form#forms')

    // convert the form to JSON
    const getFormJSON = (form) => {
      const data = new FormData(form);
      return Array.from(data.keys()).reduce((result, key) => {
        if (result[key]) {
          result[key] = data.getAll(key)
          return result
        }
        result[key] = data.get(key);
        return result;
      }, {});
    };

    // handle the form submission event, prevent default form behaviour, check validity, convert form to JSON
    const handler = (event) => {
      event.preventDefault();
      const valid = formElement.reportValidity();
      if (valid) {
        const result = getFormJSON(formElement);
        // handle one, multiple or no files uploaded
        const images = [result.images].flat().filter((file) => !!file.name)
        // handle one, multiple or no languages selected
        const languages = [result.languages || []].flat();
        // convert the checkbox to a boolean
        const isHappyReader = !!(result.isHappyReader && result.isHappyReader === 'on')

        // use spread function, but override the keys we've made changes to
        const output = {
          ...result,
          images,
          languages,
          isHappyReader
        }
        console.log(output)
      }
    }

    formElement.addEventListener("submit", handler)
  </script>
</body>
```


## Bonus: Example Test <a name="examples/test"></a>
```javascript
it('should return a JSON representation of a form', () => {
  const form = document.createElement('form');

  const input = document.createElement('input');
  input.name = 'test';
  input.value = 'value';
  form.appendChild(input);

  const number = document.createElement('input');
  number.type = 'number';
  number.name = 'int';
  number.value = '10';
  form.appendChild(number);

  const result = getFormJSON(form);
  expect(result).to.deep.equal({
    test: 'value',
    int: '10',
  });
});
```

# Summary <a name="summary"></a>

In summary, you can use what browsers give you to get all the great benefits of HTML Forms, and then convert it to JSON so it's easier to work with the data! I hope this has been useful.

Happy Form building!

Would you be interested in a series of what you can achieve with HTML and Web APIs?
What are you favourite web tips and tricks?