复杂的html表单到json对象

问题描述:

我有一个高级表单。我需要从基本的html页面表单发送给我的restapi。
我的表单由基本字段组成,例如。名称,ID等。
我也有一个对象列表。
我的问题来了,当我需要在我的对象内的对象。
例如。 jsonString对象,它是动态的,可以包含多个字段。复杂的html表单到json对象

<input type="text" name="jsonString.field1" value="123"> 
<input type="text" name="jsonString.field2" value="qwe"> 
<input type="text" name="jsonString.fieldN" value="..."> 

我要的是:

{ 
id: 411421, 
name: asdojasfjo, 
alotOfRandomFields: "Random", 
"jsonString": { 
    field1: "123", 
    field2: "qwe", 
    fieldN: "..." }, 
numbers: [1,2,3,4] 
} 

我jsonString对象字段名称可能不同,并如。 “Petname”,petage,petOwnerName和其他形式。 “工作名称”和“工资”。

我知道,如果我救他们都具有相同的名字,我得到一个数组,但我不能看到字段名称,这是需要在未来比较包含宠物的所有文件。

目前我使用jQuery的:

form.serialize(); 

任何意见或指针?

+0

我真的不明白为什么人们downvote问题没有给予反馈,为什么他们downvote ... – Kiksen

我已经解决了我的问题。不太喜欢它被解决的方式。因此,如果任何人有一个更好的主意,请分享:)

function ConvertFormToJSON(form){ 
    var array = jQuery(form).serializeArray(); 
    var json = {jsonString:{}}; 
    var substring = "jsonString"; 
    jQuery.each(array, function() { 
     if(this.name.indexOf(substring) !== -1){ 
      json["jsonString"][this.name.substring(10)] = this.value; 
     } 
     else{ 
      json[this.name] = this.value || ''; 
     } 

    }); 

    return json; 
}