如何将HTML5 FormData对象中的条目转换为JSON?

解决方案不应该使用jQuery.此外,它不应该简单地序列化整个FormData对象,而应该只序列化其键/值项.

推荐答案

您也可以直接在FormData对象上使用forEach:

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

UPDATE:

对于那些喜欢使用ES6 arrow functions的相同解决方案的人:

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

UPDATE 2:

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用简单的多选列表演示该方法的使用.

更新3:

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:

更新4:

正如在我的答案下面的一条注释中提到的,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.

Json相关问答推荐

Jolt将键和值转换为单独的数组集

如何用JQ更改空/布尔/数字的 colored颜色 ?

规范化JSON数据

遍历 JSON,检索父值

从 oracle 数据库中的 json blob 打印值

是否可以在有条件的情况下将 json 对象转换为 JOLT 中的数组?

如何使用 React 从 NASA IMAGES API 中解构所需信息

如何使用 gson 调用默认反序列化

IE8 原生 JSON.parse 错误导致堆栈溢出

Jackson 中的 readValue 和 readTree:何时使用哪个?

PostgreSQL 中的 JSON 模式验证?

Jackson:忽略 Json 配置值

在浏览器中查看 JSON 文件

如何在 Rails 模型中验证字符串是否为 json

Swift :将 struct 转换为 JSON?

如何使用 Serde 反序列化带有自定义函数的可选字段?

确保数组中的项目属性在 Json Schema 中是唯一的?

使用 JSON.NET 序列化/反序列化对象字典

log4j 支持 JSON 格式吗?

play 2 JSON 格式中缺少的属性的默认值