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:
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.
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