"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Convert HTML5 FormData to JSON Without jQuery or Serialization?

How to Convert HTML5 FormData to JSON Without jQuery or Serialization?

Posted on 2025-03-22
Browse:450

How to Convert HTML5 FormData to JSON Without jQuery or Serialization?

Converting HTML5 FormData to JSON: A Step-by-Step Guide

Problem: Converting the entries of a FormData object to JSON without jQuery or serializing the entire object.

Answer:

To convert the entries of a FormData object to JSON, follow these steps:

  1. Create an empty object to store the key/value pairs.
  2. Iterate over the FormData object using a loop or method like forEach.
  3. For each entry, set the key in the empty object to the entry's name and the value to its value.
  4. Convert the object to JSON using the JSON.stringify() method.

Example Using forEach:

var object = {};
formData.forEach(function(value, key){
    object[key] = value;
});
var json = JSON.stringify(object);

Example Using ES6 Arrow Functions:

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);

Support for Multi Select Lists:

If your form contains multi select lists or other elements with multiple values, you can use the following approach:

var object = {};
formData.forEach((value, key) => {
    if(!Reflect.has(object, key)){
        object[key] = value;
        return;
    }
    if(!Array.isArray(object[key])){
        object[key] = [object[key]];    
    }
    object[key].push(value);
});

Sending FormData to a Server:

If you intend to submit the form data to a server, you can skip the conversion to JSON and directly send the FormData object using an XMLHttpRequest or Fetch API request.

Caution:

The JSON.stringify() method may not support all types of objects. If your object contains unsupported types, you may need to implement a custom toJSON() method to specify the serialization logic.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3