【问题标题】:How to convert serialized form to json format which having a list of tags如何将序列化形式转换为具有标签列表的 json 格式
【发布时间】:2014-10-29 09:13:07
【问题描述】:

这是我的表格:

<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"
            }
    ]
}

}

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

【问题讨论】:

  • 您应该将输入的名称更改为 field1, field2 ...
  • 它是一个列表。我猜改名字不是解决办法。
  • 那么不要使用serialize,你需要对方法进行硬编码。
  • 有什么选择吗?

标签: javascript jquery ajax json forms


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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);
    

    【讨论】:

      【解决方案3】:

      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>

      【讨论】:

      • @Werd 没问题!如果这个或任何其他答案帮助您解决了您的问题,您应该mark it as accepted 表明问题已解决,并帮助其他人在未来找到它(另外,它给回答的人一点功劳)。跨度>
      猜你喜欢
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 2022-11-12
      • 2021-01-06
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多