如何通过在jQuery中序列化对象来获取正确的json结构?

时间:2013-03-30 00:24:51

标签: jquery json serialization

如何通过在jquery中序列化对象来获取正确的json结构?

我的代码如下:

<form id="myform">
<input name="Name[OrganizationName]" id="OrganizationName" />
</form>

输出的内容如下:

"Name[OrganizationName]": "Bill"}

但我想要这个:

"Name":{"OrganizationName":"Bill"} 

这是我的序列化js:

$.fn.serializeObject = 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;
};

我通过以下方式调用它:

$("#form-add-po").serializeObject();

1 个答案:

答案 0 :(得分:0)

$.fn.wrongLogic = function () {
    var o = {};
    this.find('input').each(function () {
        if (this.name.indexOf('[') > -1) {
            var prop = this.name.match(/\[(\w+)\]$/)[1],
                mainProp = this.name.split('[')[0],
                n = {},
            if (o.hasOwnProperty(mainProp)) {
                o[mainProp][prop] = this.value;
            } else {
                n[prop] = this.value;
                o[mainProp] = n;
            }
        } else {
            o[this.name] = this.value;
        }
    })
    return o;
};

http://jsfiddle.net/h2jE5/1/