Form serialization

April 03, 2025 | Work: 2025-01

The next thing I need to be able to do is “serialization” which is a fancy term for “takes all the fields in this guide and combine them into a thing that I can save to local storage”.

The web browser gives us a bunch of free behaviors, particularly around forms. What I am envisioning here is creating a single very lengthy form, and then using default browser behavior to take all the fields and dump them into a big JSON object.

So this:

[x] Get a Shovel
[x] Dig a hole
[ ] Find treasure

could become something like:

{
  "tasks": {
    "get_shovel": "true",
    "dig_hole": "true",
    "find_treasure": "false"
  }
}

The first thing we need to do is grab the form object in the JavaScript. There’s an existing API tool called FormData. If we had a form like this:

<form id="tasks">
  <label><input type="checkbox" name="tasks[get_shovel]" value="1" /> Get Shovel</label>
  <label><input type="checkbox" name="tasks[dig_hole]" value="1" /> Dig Hole</label>
  <label><input type="checkbox" name="tasks[find_treasure]" value="1" />Find Treasure</label>
</form>

We can hook into it like this:

const tasks = document.querySelector("form#tasks");
const formData = new FormData(tasks);

Now we need to convert that data into a JSON blob.

As it turns out, there was a development not long ago (2019) in browser-based JS that lets you serialize the form very easily. I found a post on StackOverflow discussing it: Object.fromEntries()

const tasks = document.querySelector("form#tasks");
const data = new FormData(tasks);

var entries = Object.fromEntries(data); //{};

checkbox form showing 2 checked boxes javascript output showing a JSON blob with 2 inclusions

Woot!