如何将 FormData(HTML5 对象)转换为 JSON [英] How to convert FormData (HTML5 object) to JSON
问题描述
如何将条目从 HTML5 FormData
对象转换为 JSON?
How do I convert the entries from a HTML5 FormData
object to JSON?
解决方案不应使用jQuery.此外,它不应简单地序列化整个 FormData
对象,而应仅序列化其键/值条目.
The solution should not use jQuery. Also, it should not simply serialize the entire FormData
object, but only its key/value entries.
推荐答案
你也可以直接在 FormData
对象上使用 forEach
:
You could also use forEach
on the FormData
object directly:
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
更新:
对于那些喜欢与 ES6 相同的解决方案的人箭头函数:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
更新 2:
对于那些想要支持多选列表或其他具有多个值的表单元素的人(因为关于这个问题的答案下面有很多评论,我将添加一个可能的解决方案)::>
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);
Here a Fiddle 用一个简单的 multi 演示了这种方法的使用选择列表.
Here a Fiddle demonstrating the use of this method with a simple multi select list.
作为结尾的补充说明,如果将表单数据转换为 json 的目的是通过 XML HTTP 请求将其发送到服务器,您可以直接发送 FormData
对象无需转换.就这么简单:
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:
正如在我的回答下面的评论之一中提到的,JSON stringify
方法不适用于所有类型的对象.有关支持哪些类型的更多信息,我想参考 JSON.stringify
的 MDN 文档中的描述部分.
As mentioned in one of the comments below my answer the JSON stringify
method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify
.
在描述中还提到:
如果该值有一个 toJSON() 方法,它负责定义将要序列化的数据.
If the value has a toJSON() method, it's responsible to define what data will be serialized.
这意味着您可以提供您自己的 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.
这篇关于如何将 FormData(HTML5 对象)转换为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!