How To Convert FormData To JSON Object

Recently, whilst working on a project I needed to take HTML FormData and then convert it to JSON to be sent off to an API. By default the FormData object does not work in the way you would want it to for JSON.

Using the for..of syntax introduced in ECMAScript 2015, we can access the form data entries and iterate over them to get key and value pairs.

const formData = new FormData(SomeFormElement);
let jsonObject = {};

for (const [key, value]  of formData.entries()) {
    jsonObject[key] = value;
}

By calling entries on our form data object, it returns the required iterable data we can then access in the form of key and value. In our above example we actually store each item in an object.

Fortunately, this isn’t a complicated problem to solve. If we had to do this without a for..of loop, then it wouldn’t be nearly as clean as the above solution is (which can still be improved).

6 responses to “How To Convert FormData To JSON Object”

  1. leo says:

    Thank you !! 🙂

  2. aretheregods says:

    You don’t need to use .entries(). You can use the formdata directly in the for…of.

  3. JD says:

    Thanks for sharing.

    Does not work with multiple keys (Used to have an array in our backend)

  4. Fede says:

    Thanks man

  5. Be aware if you want to send the jsonObject to API which expects JSON it will not work since the JSON keys are not strings (with “).
    To convert into valid JSON you still need call JSON.stringify(jsonObject).

Leave a Reply

Your email address will not be published. Required fields are marked *