且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jQuery将查询字符串或JSON对象映射转换为单个JSON对象?

更新时间:2022-05-29 22:15:51

kgiannakakis提出的遍历地图的建议是一个很好的起点,尽管我不认为这可以作为我最初问题的答案.经过几个小时的头部撞击后,我为此做好了准备,这使您可以基于自定义属性来序列化元素(我不想因为必须在我的表单元素上使用'name'属性而感到满足).我还开始使用json.org中的JSON库来对我创建的对象进行字符串化.我的插件的 serializeToJSON 函数是我在寻找问题的答案时所需要的功能,其余只是exta.

kgiannakakis's suggestion to traverse the map was a good starting point, though I don't feel that it qualifies as an answer to my original question. After a couple of hours of head banging, I settled for this, which allows you to serialize elements based on a custom attribute (I didn't want to settle for having to use the 'name' attribute on my form elements, which jQuery requires). I have also started using the JSON library from json.org in order to stringify the object I create. The serializeToJSON function of my plugin is what I was looking for as an answer to my question, the rest is just exta.

注意:这是针对客户端的,因此"CustomXXX"的名称和属性将替换为它们的实际名称

Note: This is for a client, so the 'CustomXXX' names and attributes were substituted in for what they actually are

jQuery.fn.extend({
    serializeCustomPropertyArray: function() {
        return this.map(function() {
            return this.elements ? jQuery.makeArray(this.elements) : this;
        }).filter(function() {
            return jQuery(this).attr('CustomAttribute') &&
                (this.checked || /select|textarea/i.test(this.nodeName) ||
                        /text|hidden|password|search/i.test(this.type));
        }).map(function(i, elem) {
            var val = jQuery(this).val();
            return val == null ? null : jQuery.isArray(val) ?
                jQuery.map(val, function(val, i) {
                    return { name: jQuery(elem).attr('CustomAttribute'), value: val };
                }) : { name: jQuery(elem).attr('CustomAttribute'), value: val };
        }).get();
    },
    serializeToJSON: function() {
        var objectMap = this.serializeCustomPropertyArray();
        var objectJson = new Object;
        jQuery.each(objectMap, function() {
            objectJson[this.name] = (this.value !== null) ? this.value : 'null';
        });
        return JSON.stringify(objectJson);
    }
});

可以这样称呼:

$('#fields').find(':input[CustomGroup="Months"]').serializeToJSON();

假设您的文档看起来像这样:

Assuming your document looks something like:

<div id="fields">
   <input type="checkbox" CustomGroup="Months" CustomAttribute="January" />January<br />
   <input type="checkbox" CustomGroup="Months" CustomAttribute="February" />February<br />
   ...
</div>

构建的JSON看起来像:

The JSON that's built looks like:

{ January: 'on', February: 'on', ... }