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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/789755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:47:46  来源:igfitidea点击:

How can I convert query string or JSON object map to single JSON object with jQuery?

jqueryjsonquery-string

提问by C???

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. Convert a query string (e.g. "January=on&March=on&September=on") or
  2. Convert an object map: [{ January: 'on' },{ March: 'on' },{ September: 'on' }]
  1. 转换查询字符串(例如"January=on&March=on&September=on")或
  2. 转换对象映射: [{ January: 'on' },{ March: 'on' },{ September: 'on' }]

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

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

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

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

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

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

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

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

这就是为什么我可以处理第一个或第二个答案。

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:

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

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

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!

那么,是否有人知道可以轻松完成此操作的 JSON 插件(我只想坚持使用 jQuery),或者知道实现我正在寻找的结果的简单方法?谢谢!

回答by Rahen Rangan

You can try this

你可以试试这个

String.prototype.QueryStringToJSON = function () {
href = this;
qStr = href.replace(/(.*?\?)/, '');
qArr = qStr.split('&');
stack = {};
for (var i in qArr) {
    var a = qArr[i].split('=');
    var name = a[0],
        value = isNaN(a[1]) ? a[1] : parseFloat(a[1]);
    if (name.match(/(.*?)\[(.*?)]/)) {
        name = RegExp.;
        name2 = RegExp.;
        //alert(RegExp.)
        if (name2) {
            if (!(name in stack)) {
                stack[name] = {};
            }
            stack[name][name2] = value;
        } else {
            if (!(name in stack)) {
                stack[name] = [];
            }
            stack[name].push(value);
        }
    } else {
        stack[name] = value;
    }
}
return stack;
}

Query String

请求参数

    href="j.html?name=nayan&age=29&salary=20000&interest[]=php&interest[]=jquery&interest[1]=python&interest[2]=Csharp&fan[friend]=rangan&fan[family]=sujan&sports[1]=cricket&sports[2]=football";

usage

用法

alert(href.QueryStringToJSON().toSource())

output

输出

({name:"nayan", age:29, salary:20000, interest:["php", "python", "Csharp"], fan:{friend:"rangan", family:"sujan"}, sports:{1:"cricket", 2:"football"}})

回答by C???

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 serializeToJSONfunction of my plugin is what I was looking for as an answer to my question, the rest is just exta.

kgiannakakis 提出的遍历地图的建议是一个很好的起点,尽管我认为它不能作为我最初问题的答案。经过几个小时的头撞后,我解决了这个问题,它允许您根据自定义属性序列化元素(我不想满足于必须在我的表单元素上使用 'name' 属性,这是 jQuery 要求的) )。我还开始使用来自 json.org 的 JSON 库来对我创建的对象进行字符串化。我的插件的serializeToJSON函数是我正在寻找的问题的答案,其余的只是额外的。

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

注意:这是针对客户的,因此“CustomXXX”名称和属性被替换为实际情况

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

This can be called like:

这可以被称为:

$('#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>

The JSON that's built looks like:

构建的 JSON 如下所示:

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

回答by kgiannakakis

You can traverse an object map using the $.eachutility function.

您可以使用$.each实用程序函数遍历对象映射。

$(function() {
    map = [{ January: 'on' },{ March: 'on' },{ September: 'on' }];
    $.each(map, function() {
       $.each(this, function(key, val) {alert(key + " = " + val);});;
    });
});

The first each gets you all array objects. With the second one you can get the key and value of your object.

第一个每个都会为您提供所有数组对象。使用第二个,您可以获得对象的键和值。

回答by Jeoff Wilks

I know you're trying to turn a query-string into a JSON object, but perhaps you might be interested in going directly from an html form to a JSON object (without having to specify really convoluted name attributes). If so, check out JSONForms: http://code.google.com/p/jsonf/

我知道您正在尝试将查询字符串转换为 JSON 对象,但也许您可能对直接从 html 表单转到 JSON 对象感兴趣(无需指定非常复杂的名称属性)。如果是这样,请查看 JSONForms:http: //code.google.com/p/jsonf/

Disclaimer: I started the jsonforms project. It's still young, but personally I think it rocks!

免责声明:我开始了 jsonforms 项目。它仍然很年轻,但我个人认为它很摇滚!

回答by Alex

You can also use the parseQuery pluginto create an object from the serialized elements.

您还可以使用parseQuery 插件从序列化元素创建对象。

var contact = $.parseQuery($("#step1 *").serialize());