Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/408.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将序列化的表单转换为json格式,其中包含一个标记列表_Javascript_Jquery_Ajax_Json_Forms - Fatal编程技术网

Javascript 如何将序列化的表单转换为json格式,其中包含一个标记列表

Javascript 如何将序列化的表单转换为json格式,其中包含一个标记列表,javascript,jquery,ajax,json,forms,Javascript,Jquery,Ajax,Json,Forms,这是我的表格: <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

这是我的表格:

<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>
以下是我的预期结果:

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

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

请参阅

serializeArray()
仅获取单个对象中字段的
name
value
属性。如果您想自定义得到的输出,您需要编写自己的函数,这样您就可以创建自己的自定义数组,并在自定义数组上调用
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
方法不会解析字段名以派生层次结构;您必须手动编写代码,但不会太困难。如果您有一个定义良好的格式,您可以尝试下面的代码。如果您需要一个更通用的解决方案,允许多个嵌套级别和不同的父级名称,那么您需要构建功能更全面的解决方案

$(函数(){
var$form=$(“form”);
var regex=/.*childobject\[(\d)\].*/;
变量rgxForField=/.*childobject.*(字段\d)/;
var obj={“parentobject”:{};
var childObjects=[];
obj[“父对象”][“子对象”]=子对象;
$form.find(“输入[name^='parentobject.childobj']”)。每个(函数(){
var idx=parseInt(this.name.match(regex)[1],10);
如果(!childObjects[idx])childObjects[idx]={};
var fieldName=this.name.match(rgxForField)[1];
childObjects[idx][fieldName]=此.value;
});
控制台日志(obj);
$form.after($(“”,{text:JSON.stringify(obj)}));
$form.remove();
});

您可以使用函数

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))
var parentobject={
childobject:[{},{}]
}
var arr=$('form').serializeArray();

对于(var i=0;iyou应该将输入的名称更改为field1,field2…这是一个列表。我想更改名称不是解决方案。然后不要使用serialize,您需要硬编码该方法。是否有任何选项?@Werd没问题!如果这个或任何其他答案帮助你解决了问题,你应该证明问题已经解决,并帮助其他人在将来找到它(另外,它给了回答者一点信任)。
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))