Formson is a FormData to JSON converter.
It supports:
- Dot notation to create nested objects
- Square bracket notation to create arrays
- Mixed object/array structures
Sponsored by Formspark, the simple & powerful form solution for developers.
Install the package.
npm install @formspark/formsonYou can now import the toJSON function to convert a FormData object to a JSON object.
import{toJSON}from"@formspark/formson";constjson=toJSON(formData);Add the Formson script.
<scriptsrc="https://unpkg.com/@formspark/formson"></script>You can now use the Formson.toJSON function to convert a FormData object to a JSON object.
constjson=Formson.toJSON(formData);<!doctype html><htmllang="en"><head><scriptsrc="https://unpkg.com/@formspark/formson"></script></head><body><h1>Example</h1><formid="form"><inputname="firstName" /><inputname="lastName" /><buttontype="submit">Submit</button></form><script>document.getElementById("form").addEventListener("submit",function(event){event.preventDefault();constformData=newFormData(this);constjson=Formson.toJSON(formData);alert(JSON.stringify(json));});</script></body></html>Dot notation uses periods (.) to create nested objects.
<form><inputname="user.firstName" value="John" /><inputname="user.lastName" value="Doe" /></form>This will result in the following JSON structure:
{
"user": {
"firstName": "John",
"lastName": "Doe"
}
}Square bracket notation uses square brackets ([]) to create arrays.
<form><inputname="users[0]" value="Alice" /><inputname="users[1]" value="Bob" /><inputname="users[2]" value="Charlie" /></form>This will result in the following JSON structure:
{
"users": ["Alice", "Bob", "Charlie"]
}A field name repeated without brackets, such as a checkbox group, also becomes an array.
<form><inputtype="checkbox" name="interests" value="music" checked/><inputtype="checkbox" name="interests" value="sports" checked/></form>{
"interests": ["music", "sports"]
}You can mix dot and square bracket notation to create complex structures.
<form><inputtype="text" name="user.name" value="John Doe" /><inputtype="text" name="user.skills[0]" value="JavaScript" /><inputtype="text" name="user.skills[1]" value="TypeScript" /><inputtype="text" name="user.address.street" value="123 Main St" /><inputtype="text" name="user.address.city" value="Anytown" /><inputtype="text" name="user.projects[0].name" value="Project A" /><inputtype="text" name="user.projects[0].tasks[0]" value="Task 1" /><inputtype="text" name="user.projects[0].tasks[1]" value="Task 2" /><inputtype="text" name="user.projects[1].name" value="Project B" /><inputtype="text" name="user.projects[1].tasks[0]" value="Task 3" /><buttontype="submit">Submit</button></form>This will result in the following JSON structure:
{
"user": {
"name": "John Doe",
"skills": ["JavaScript", "TypeScript"],
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"projects": [
{
"name": "Project A",
"tasks": ["Task 1", "Task 2"]
},
{
"name": "Project B",
"tasks": ["Task 3"]
}
]
}
}