如何将FormData(HTML5对象)转换为JSON [英] How to convert FormData (HTML5 object) to JSON

查看:582
本文介绍了如何将FormData(HTML5对象)转换为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 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);

请参见使用FormData对象在MDN上以供参考:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆