这是我的表格:
<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"
}
]
}
我希望有人能提供帮助。提前致谢。
最佳答案
你可以使用 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
关于javascript - 如何将序列化形式转换为具有标签列表的json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26626418/