如何将HTML5 FormData
对象中的条目转换为JSON?
解决方案不应该使用jQuery.此外,它不应该简单地序列化整个FormData
对象,而应该只序列化其键/值项.
如何将HTML5 FormData
对象中的条目转换为JSON?
解决方案不应该使用jQuery.此外,它不应该简单地序列化整个FormData
对象,而应该只序列化其键/值项.
您也可以直接在FormData
对象上使用forEach
:
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
对于那些喜欢使用ES6 arrow functions的相同解决方案的人:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):
var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);
100用简单的多选列表演示该方法的使用.
As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData
object directly without converting it. As simple as this:
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
See also Using FormData Objects on MDN for reference:
正如在我的答案下面的一条注释中提到的,JSONstringify
方法并不是对所有类型的对象都可以开箱即用.有关支持哪些类型的更多信息,我想参考the Description section in the MDN documentation of JSON.stringify
.
In the description is also mentioned that:
如果该值有一个toJSON()方法,则它负责定义将序列化哪些数据.
This means that you can supply your own toJSON
serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.