如何将序列化的表单转换为具有标签列表的json格式

How to convert serialized form to json format which having a list of tags

本文关键字:标签 列表 格式 json 转换 序列化 表单      更新时间:2023-09-26

这是我的表单:

<form>
 <input type="text" value="value1a" name="parentobject.childobject[0].field1"/>
 <input type="text" value="value2a" name="parentobject.childobject[0].field2"/>
 <input type="text" value="value3a" name="parentobject.childobject[0].field3"/>
 <input type="text" value="value1b" name="parentobject.childobject[1].field1"/>
 <input type="text" value="value2b" name="parentobject.childobject[1].field2"/>
 <input type="text" value="value3b" name="parentobject.childobject[1].field3"/>
</form>

当我使用JSON.stringfy($('form').serializeArray())时,值转换为JSON,但不是我预期的结果。

使用JSON.stringfy($('form).serializedArray())后的输出

{
 "parentobject.childobject[0].field1" : "value1a"
 "parentobject.childobject[0].field2" : "value2a"
 "parentobject.childobject[0].field3" : "value3a"
 "parentobject.childobject[1].field1" : "value1b"
 "parentobject.childobject[1].field2" : "value2b"
 "parentobject.childobject[1].field3" : "value3b"
} 

这是我预期的结果:

 {
    "parentobject": {
        "childobject": [
            {
                "field1": "value1a",
                "field2": "value2a",
                "field3": "value3a"
           },
            {
                "field1": "value1b",
                "field2": "value2b",
                "field3": "value3b"
            }
    ]
}

}

我希望有人能帮忙。提前谢谢。

您可以使用eval()功能

var parentobject = {
    childobject: [{}, {}]
}
var arr = $('form').serializeArray();
for(var i=0;i<arr.length;i++)
{
eval(arr[i].name+"='"+arr[i].value+"'");
}
alert(JSON.stringify(parentobject))

演示

请参阅http://jsfiddle.net/vorj5o1b/1/

serializeArray()只获取单个对象中字段的namevalue属性。如果你想自定义你得到的输出,你需要编写自己的函数,这样你就可以创建自己的自定义数组,并在自定义数组上调用stringify

var myArray = [];
var fields = $("#f").serializeArray();
var obj = {};
var childObj = {};
var firstIndex = 0;
jQuery.each(fields, function(i, field){
    var parentName = field.name.split('.')[0];
    var childName = field.name.split('.')[1].split("[")[0];
    var childIndex = parseInt(field.name.split('.')[1].split("[")[1].split("]")[0]);
    var fieldName = field.name.split('.')[2];
    if (!obj[parentName]){ //If obj doesn't have the parentName object, create it.
        obj[parentName] = {};
    }
    if (!obj[parentName][childName]){ //if obj[parentName] doesn't have an array yet, create it
        obj[parentName][childName] = [];
    }
    if (firstIndex !== childIndex){ //when it moves from [0] to [1]
        firstIndex = childIndex;
        obj[parentName][childName].push(childObj); //push childObj to obj array
        childObj = {};
    }
    childObj[fieldName] = field.value;
    if (i == fields.length - 1){ //needs an extra if here to add the final childObj
         obj[parentName][childName].push(childObj);
    }
});
myArray.push(obj); //use custom array

var myString = JSON.stringify(myArray); //stringify custom array
console.log(myString);
jQuery serializeArray方法不会解析字段名来派生层次结构;你必须手动编码,但这并不太难。如果您有一个定义良好的格式,您可以尝试下面的代码。如果您需要一个更通用的解决方案,允许多个级别的嵌套和不同的父名称,那么您需要构建功能更全面的解决方案。

$(function() {
    
    var $form = $("form");
    var regex = /.*childobject'[('d)'].*/;
    var rgxForField = /.*childobject.*(field'd)/;
    var obj = {"parentobject" : {} };
    var childObjects = [];
    obj["parentobject"]["childobject"] = childObjects;
    $form.find("input[name^='parentobject.childobj']").each(function() {
        var idx = parseInt(this.name.match(regex)[1], 10);
        if (!childObjects[idx]) childObjects[idx] = {};
        var fieldName = this.name.match(rgxForField)[1];
        childObjects[idx][fieldName] = this.value;
    });
    console.log(obj);
    $form.after($("<div/>", { text: JSON.stringify(obj)}));
    $form.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
 <input type="text" value="value1a" name="parentobject.childobject[0].field1"/>
 <input type="text" value="value2a" name="parentobject.childobject[0].field2"/>
 <input type="text" value="value3a" name="parentobject.childobject[0].field3"/>
 <input type="text" value="value1b" name="parentobject.childobject[1].field1"/>
 <input type="text" value="value2b" name="parentobject.childobject[1].field2"/>
 <input type="text" value="value3b" name="parentobject.childobject[1].field3"/>
</form>