从动态表单创建嵌套JSON

时间:2017-11-13 00:24:10

标签: javascript jquery json api

我有一个客户端的自定义页面构建器,他们可以通过拖放后端构建自己的Web表单。

目前,我可以使用JSON格式输出数据,如下所示:

{ 
  "email":"xx@yy.com",
  "geoip_country":"XXYY",
  "geoip_state":"XXYY",
  "geoip_city":"XXYY",
}

但是,我需要以下列格式更改输出,我想从表单中分离出电子邮件字段,并删除嵌套在dynamic_attributes部分中的所有其他数据,如下所示:

{
    "email":"xx@yy.com",
    "dynamic_attributes":{
        "geoip_country":"XXYY",
        "geoip_state":"XXYY",
        "geoip_city":"XXYY",
        // all other form fields here.

    },
}

有人能指出我正确的方向吗?我在输出JSON方面经验不足 - 我还应该补充说json是从以下jQuery函数创建的:

(function ($) {
    $.fn.serializeFormJSON = function () {

        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);

请参阅小提琴:https://jsfiddle.net/fish_r/m46zLdo9/3/

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:



$('#myform').submit(function(e) {
    e.preventDefault();
    var data = $(this).serializeFormJSON();
    console.log(data);
});

(function ($) {
    $.fn.serializeFormJSON = function () {
		
        var o = {};
        var dynamic_attributes = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (this.name =='email') {
              if (o[this.name]) {
                  if (!o[this.name].push) {
                      o[this.name] = [o[this.name]];
                  }
                  o[this.name].push(this.value || '');
              } else {
                  o[this.name] = this.value || '';
              }
            } else {
              if (dynamic_attributes[this.name]) {
                  if (!dynamic_attributes[this.name].push) {
                      dynamic_attributes[this.name] = [dynamic_attributes[this.name]];
                  }
                  dynamic_attributes[this.name].push(this.value || '');
              } else {
                  dynamic_attributes[this.name] = this.value || '';
              }   
            }
        });
        o['dynamic_attributes'] = dynamic_attributes;
        
        return o;
    };
})(jQuery);

.hidden {opacity:.3}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST" id="myform">
  <input type="text" name="name" placeholder="name"><br/>
  <input type="email" name="email" placeholder="Enter your email"><br/>
  <input type="text" name="address1" placeholder="Enter the first line of your address"><br/>
  <input type="submit">
</form>
<div id="output"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

To anyone looking for help on a similar issue in the future, I've created a library to allow forms to be sent as deep nested JSON objects by writing the name attributes of each input as a series of subkeys joined by "." characters.

要导入库:

<script src="https://cdn.jsdelivr.net/npm/deepforms@1.0.0/deepforms.min.js"></script>

使用该库制作的示例表单:

<form id = "exampleForm" method = "POST" action = "/submitForm">
    <input type = "text" name = "user.name" value = "testUser">
    <input type = "text" name = "color" value = "blue">
    <input type = "text" name = "color" value = "red">
</form>
<button onclick="document.deepforms.submitDeepForm('exampleForm')">

单击提交按钮后,将生成以下对象并将其作为JSON字符串发送:

{
    "user" : {
        "name" : "testUser"
    },
    "color" : ["blue", "red"]
}

JSON字符串作为名为deepFormJSON的参数的值发送:

deepFormJSON : '{"user":{"name":"testUser"},"color":["blue","red"]}}'

可以将其解析为JSON字符串,以便在请求目标处构造对象。