繁体   English   中英

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

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

这是我的表格:

<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.stringify($('form')。serializeArray())时,值转换为json但不是我预期的结果。

使用JSON.stringify后的输出($('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"
            }
    ]
}

}

我希望有人可以提供帮助。 提前致谢。

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> 

您可以使用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))

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM