Javascript 如何将 jQuery.serialize() 数据转换为 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3277655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:00:21  来源:igfitidea点击:

How to convert jQuery.serialize() data to JSON object?

javascriptjqueryjsonserialization

提问by Raftalks

Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to be able to convert the form data in to a JSON object to recreate some other informative tables. So tell me a better way to get the serialize string converted as a JSON object.

当表单包含多个输入 Array 字段时,是否有更好的解决方案来转换已由 jQuery 函数 serialize() 序列化的表单数据。我希望能够将表单数据转换为 JSON 对象以重新创建一些其他信息表。所以告诉我一个更好的方法来将序列化字符串转换为 JSON 对象。

<form id='sampleform'>
    <input name='MyName' type='text' /> // Raf

    <!--array input fields below-->
    <input name='friendname[]' type='text' /> // Bily
    <input name='fiendemail[]' type='text' /> // [email protected]

    <!--duplicated fields below to add more friends -->
    <input name='friendname[]' type='text' /> // Andy
    <input name='fiendemail[]' type='text' /> // [email protected]

    <input name='friendname[]' type='text' /> // Adam
    <input name='fiendemail[]' type='text' /> // [email protected]
</form>

The jquery method applied to get the data

用于获取数据的jquery方法

var MyForm = $("#sampleform").serialize();
/** result : MyName=Raf&friendname[]=Billy&fiendemail[][email protected]&friendname[]=Andy&fiendemail[][email protected]&friendname[]=Adam&fiendemail[][email protected]
*/

how do I make this data in to a JSON object? which should have the following example JSON data from the above form.

如何将这些数据转换为 JSON 对象?它应该具有来自上述表单的以下示例 JSON 数据。

{
    "MyName":"raf",
    "friendname":[
        {"0":"Bily"},
        {"1":"Andy"},
        {"2":"Adam"}
    ],
    "friendemail":[
        {"0":"[email protected]"},
        {"1":"[email protected]"},
        {"2":"[email protected]"}
    ]
}

回答by Danilo Colasso

var formdata = $("#myform").serializeArray();
var data = {};
$(formdata ).each(function(index, obj){
    data[obj.name] = obj.value;
});

Simple and fast ;)

简单快速;)

回答by Samuel Meacham

I have recently had this exact problem. Initially, we were using jQuery's serializeArray()method, but that does not include form elements that are disabled. We will often disable form elements that are "sync'd" to other sources on the page, but we still need to include the data in our serialized object. So serializeArray()is out. We used the :inputselector to get all input elements (both enabled and disabled) in a given container, and then $.map()to create our object.

我最近遇到了这个确切的问题。最初,我们使用 jQuery 的serializeArray()方法,但这不包括禁用的表单元素。我们经常会禁用与页面上其他源“同步”的表单元素,但我们仍然需要将数据包含在我们的序列化对象中。所以serializeArray()出来了。我们使用:input选择器获取给定容器中的所有输入元素(启用和禁用),然后$.map()创建我们的对象。

var inputs = $("#container :input");
var obj = $.map(inputs, function(n, i)
{
    var o = {};
    o[n.name] = $(n).val();
    return o;
});
console.log(obj);

Note that for this to work, each of your inputs will need a nameattribute, which will be the name of the property of the resulting object.

请注意,要使其正常工作,您的每个输入都需要一个name属性,该属性将是结果对象的属性名称。

That is actually slightly modified from what we used. We needed to create an object that was structured as a .NET IDictionary, so we used this: (I provide it here in case it's useful)

这实际上与我们使用的内容略有不同。我们需要创建一个结构为 .NET IDictionary 的对象,所以我们使用了这个:(我在这里提供它,以防它有用)

var obj = $.map(inputs, function(n, i)
{
    return { Key: n.name, Value: $(n).val() };
});
console.log(obj);

I like both of these solutions, because they are simple uses of the $.map()function, and you have complete control over your selector (so, which elements you end up including in your resulting object). Also, no extra plugin required. Plain old jQuery.

我喜欢这两种解决方案,因为它们是$.map()函数的简单使用,并且您可以完全控制您的选择器(因此,您最终将哪些元素包含在结果对象中)。此外,不需要额外的插件。普通的旧jQuery。

回答by tothemario

Use the jQuery.serializeJSONplugin. It converts forms using the same format as what you would find in a Rails params object, which is very standard and well tested.

使用jQuery.serializeJSON插件。它使用与您在 Rails params 对象中找到的格式相同的格式转换表单,这是非常标准且经过良好测试的。

回答by S.C.

I'm using this very little jQuery plugin, that I've extended from DocumentCloud:

我正在使用这个非常小的 jQuery 插件,它是从 DocumentCloud 扩展而来的:

https://github.com/documentcloud/documentcloud/blob/master/public/javascripts/lib/jquery_extensions.js

https://github.com/documentcloud/documentcloud/blob/master/public/javascripts/lib/jquery_extensions.js

It is basically two lines of code, but it requires _.js (Underscore.js), since it is based on a reducefunction.

它基本上是两行代码,但它需要 _.js (Underscore.js),因为它基于一个reduce函数。

$.fn.extend({
  serializeJSON: function(exclude) {
    exclude || (exclude = []);
    return _.reduce(this.serializeArray(), function(hash, pair) {
      pair.value && !(pair.name in exclude) && (hash[pair.name] = pair.value);
      return hash;
    }, {});
  }
});

Extensions:

扩展:

  • It doesn't serialize an input value if it's null
  • It can exclude some inputs by passing an array of input names to the excludeargument i.e. ["password_confirm"]
  • 如果它为空,它不会序列化输入值
  • 它可以通过将输入名称数组传递给exclude参数来排除某些输入i.e. ["password_confirm"]

回答by Simon Trichereau

I think there're a lot of good answer here, and I made my own function based on these answers.

我认为这里有很多很好的答案,我根据这些答案制作了自己的函数。

function formToJSON(f) {
    var fd = $(f).serializeArray();
    var d = {};
    $(fd).each(function() {
        if (d[this.name] !== undefined){
            if (!Array.isArray(d[this.name])) {
                d[this.name] = [d[this.name]];
            }
            d[this.name].push(this.value);
        }else{
            d[this.name] = this.value;
        }
    });
    return d;
}

//The way to use it :
$('#myForm').submit(function(){
    var datas = formToJSON(this);
    return false;
});

Well let me explain basically why I prefer this solution... If you have multiples input with the same name, all values will be stored in an Array but if not, the value will be stored directly as the value of the index in the JSON ... This is where it's different from Danilo Colasso's answerwhere the JSON returned is only based of array values...

好吧,让我基本上解释一下为什么我更喜欢这个解决方案......如果你有多个同名输入,所有值都将存储在一个数组中,但如果没有,该值将直接存储为 JSON 中的索引值...这是它与Danilo Colasso 的答案不同地方,其中返回的 JSON 仅基于数组值...

So if you have a Form with a textarea named contentand multiples authors, this function will return to you :

因此,如果您有一个名为content和多个作者的文本区域的表单,则此函数将返回给您:

{
    content : 'This is The Content',
    authors : 
        [
            0: 'me',
            1: 'you',
            2: 'him',
        ]
}

回答by LSerni

An equivalent solution to Danilo Colasso's, with the sames pros and cons of .serializeArray()(basically it uses .reduceinstead of $.each).

Danilo Colasso's的等效解决方案,具有相同的优点和缺点.serializeArray()(基本上它使用.reduce而不是$.each)。

With little effort it allows implementing the extra features in S.C.'s answers without requiring extensions.

只需很少的努力,它就可以在不需要扩展的情况下实现 SC 答案中的额外功能。

$(selector).serializeArray()
    .reduce(function(accum, item) {
        // This 'if' allows ignoring some values
        if (-1 === [ 'ignoreThis', 'andThat' ].indexOf(item.name)) {
            // This allows ignoring NULL values
            if (item.value !== null) {
                accum[item.name] = item.value;
            }
        }
        return accum;
    },
    {
        // By supplying some initial values, we can add defaults
        // for, say, disabled form controls.
        preFilledName:  preFilledValue, // optional
        defaultName  :  defaultValue    // optional
    }
);

回答by Deepak Bansode

var formdata = $("#myform").serializeArray();

var data = {};

$(formdata ).each(function(index, obj){

         if(data[obj.name] === undefined)
              data[obj.name] = [];

          data[obj.name].push(obj.value);

});

回答by alejandro

Using underscore & jQuery

使用下划线 & jQuery

var formdata = $("#myform").serializeArray();
var data = {};
_.each(formdata, function(element){
// Return all of the values of the object's properties.
  var value = _.values(element);
// name : value 
  data[value[0]] = value[1];
});
console.log(data); //Example => {name:"alex",lastname:"amador"}

回答by Aqib

Using the power of reducing function!

使用还原功能的力量!

$(form).serializeArray().reduce(function (output, value) {
        output[value.name] = value.value

        return output
}, {})

回答by Haritsinh Gohil

if you are using ajax requests then no need to make it json-objectonly $('#sampleform').serialize()works excellently or if you have another purpose here is my solution:

如果你正在使用AJAX请求则没有必要作出它json-object只是$('#sampleform').serialize()工作出色,或者如果你有其他的目的,这里是我的解决方案:

var formserializeArray = $("#sampleform").serializeArray();   
var jsonObj = {};
jQuery.map(formserializeArray , function (n, i) {
    jsonObj[n.name] = n.value;
});