Explain Codes LogoExplain Codes Logo

How to convert FormData (HTML5 object) to JSON

javascript
form-data
json-stringification
fetch-api
Nikita BarsukovbyNikita Barsukov·Feb 16, 2025
TLDR

Turn FormData to JSON with this one-liner:

const formDataToJson = (formData) => JSON.stringify(Object.fromEntries(formData)); const formElement = document.querySelector('form'); const jsonData = formDataToJson(new FormData(formElement));

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:

const formDataToJson = (formData) => { const object = {}; formData.forEach((value, key) => { if (!object.hasOwnProperty(key)) { object[key] = value; } else { // If Key exists, hands up - this is an array! if (!Array.isArray(object[key])) { object[key] = [object[key]]; // Not an array? Make it one! } object[key].push(value); // Add new value to the array. } }); return JSON.stringify(object); // Present JSON. Tada! 🎉 };

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:

fetch('https://example.com/submit', { method: 'POST', body: jsonData, headers: { 'Content-Type': 'application/json' // JSON on board, announce arrival! } });

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:

class CustomObject { constructor(prop1, prop2) { this.prop1 = prop1; this.prop2 = prop2; } toJSON() { // Custom logic for custom needs, exactly as you'd order! return { compositeProperty: `${this.prop1}_${this.prop2}` }; } } const customObj = new CustomObject('Fuel', 'Spark'); const jsonData = JSON.stringify(customObj); // Ignite the JSON rocket! 🚀

The toJSON() method ensures your object gets the perfect JSON representation it deserves.