How to convert FormData (HTML5 object) to JSON
Turn FormData to JSON with this one-liner:
Just swap out formElement with your form DOM node and jsonData is good to go!
Understanding the fast solution
Let's unwrap the fast answer. The Object.fromEntries() function takes an array of key-value pairs and constructs an object out of it. When coupled with FormData entries, it conveniently transforms field data into an ordinary object, which JSON.stringify can turn into JSON.
Coping with multiple values
Have a form field returning multiple values like from a multi-select? Here's how to pack those arrays properly:
Here the object.hasOwnProperty(key) check and consequent conversion to an array permit retaining all associated values of a given key, without any losses!
Server-side dispatch
Planning to send this JSON to a server? Here's where the Fetch API comes to play:
Don't forget to set the Content-Type header to 'application/json' so the server knows what to expect.
Serializing custom figures
Custom objects may need some finesse while serializing. You might want to define a toJSON() method, the superhero JSON.stringify calls into action:
The toJSON() method ensures your object gets the perfect JSON representation it deserves.
Was this article helpful?