javascript - 将表单字段转换为 JSON 对象

标签 javascript jquery json html

我有以下表格:

<form id="myForm" method="POST">        
    <input type="text" name="matrix[]" value="1"/><br/>
    <input type="text" name="matrix[]" value="2"/><br/>
    <input type="text" name="matrix[]" value="3"/><br/>     
    <input type="text" name="multi_matrix[colors][]" value="red"/><br/>
    <input type="text" name="multi_matrix[colors][]" value="blue"/><br/>        
    <input type="text" name="multi_matrix[weight][]" value="75"/><br/>
    <input type="text" name="multi_matrix[weight][]" value="83"/><br/>      
    <input type="submit" value="Send">
</form>

现在我想使用 JavaScript/jQuery 将这些值转换为 JSON 字符串。当我使用 JSON.stringify($("#myForm").serializeArray()) 代码时,它返回以下内容:

[{"name":"matrix[]","value":"1"},{"name":"matrix[]","value":"2"},{"name":"matrix[]","value":"3"},{"name":"multi_matrix[colors][]","value":"red"},{"name":"multi_matrix[colors][]","value":"blue"},{"name":"multi_matrix[weight][]","value":"75"},{"name":"multi_matrix[weight][]","value":"83"}]

正如您所看到的,所有字段都有一个单独的条目,但我想将它们连接在一起以获得以下内容:

{"matrix":[1,2,3],"multi_matrix":{"colors":["red","blue"],"weight":[75,83]}}

有没有内置函数可以做到这一点?或者我是否必须迭代所有字段并自己手动创建 JSON?

最佳答案

您可以扩展 jQuery 并创建 UDF serializeObject,就像 this answer 中所做的那样,基于serializeArray() :

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

关于javascript - 将表单字段转换为 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832425/

相关文章:

javascript - 将 class = "txt"的 textxboxes 的长度设置为 width = "200"

javascript - 求json字符串的长度

javascript - 获取一周中的所有天数

javascript - 如何根据文档高度以 Angular 隐藏 div?

javascript - AngularJS 绑定(bind)模型选择最小最大值更新输入数字字段

javascript - 掩码文本输入以验证 MM/YY jquery-mask-plugin

jquery - 在加载时折叠自定义 jquery Accordion

javascript - 从句子中删除停用词

javascript - 将字符串转换为 JSON

javascript - window.devicePixelRatio 改变监听器