如何使用jQuery将查询字符串或JSON对象映射转换为单个JSON对象? [英] How can I convert query string or JSON object map to single JSON object with jQuery?

查看:78
本文介绍了如何使用jQuery将查询字符串或JSON对象映射转换为单个JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,假设我有一个表格中的月份列表,每个月份旁边都有一个复选框.我在做以下两件事中都在寻求帮助:

For this example, assume that I have a list of months in a form, each with a checkbox next to them. I'm looking for help on doing either of two things:

  1. 转换查询字符串(例如"January=on&March=on&September=on")或
  2. 转换对象图:[{ January: 'on' },{ March: 'on' },{ September: 'on' }]
  1. Convert a query string (e.g. "January=on&March=on&September=on") or
  2. Convert an object map: [{ January: 'on' },{ March: 'on' },{ September: 'on' }]

到单个JSON对象:{ January: 'on', March: 'on', September: 'on' }

to a single JSON object: { January: 'on', March: 'on', September: 'on' }

我意识到第一个映射已经是JSON,但是我希望它不是对象数组,而是单个JSON对象.我可以使用$('form').serializeArray();构建地图,也可以使用$('form').serialize();构建查询字符串.

I realize that the first map is already JSON, but instead of the object array I'd like it to be a single JSON object. I can build the map with $('form').serializeArray(); and I can build the query string with $('form').serialize();.

.serialize()在jQuery API中的实现很简单:

The implementation of .serialize() in the jQuery API is simply:

serialize: function() {
    return jQuery.param(this.serializeArray());
},

这就是为什么我可以处理第一个或第二个答案的原因.

which is why I could handle either the first or second answer.

我想这样做的原因是因为我正从PrototypeJS切换到jQuery,而在PrototypeJS中,这很简单:

The reason I'd like to do this is because I'm switching from PrototypeJS to jQuery, and in PrototypeJS this was as simple as:

Object.toJSON(Form.serializeElements($('myform'), true));

那么,有人知道可以轻松做到这一点的JSON插件(我只想坚持使用jQuery),还是知道实现我想要的结果的简单方法?谢谢!

So, does anybody know of a JSON plug-in (I'd like to stick with ONLY jQuery) that could do this easily, or know of a simple method to achieve the result I'm looking for? Thanks!

推荐答案

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', ... }

这篇关于如何使用jQuery将查询字符串或JSON对象映射转换为单个JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆