gpt4 book ai didi

jquery - 如何(完全)将查询字符串转换为 JSON 对象?

转载 作者:行者123 更新时间:2023-12-03 22:44:58 26 4
gpt4 key购买 nike

如果我有以下表格:

<form>
<input name="foo" value="bar">
<input name="hello" value="world">
<input name="animals[]" value="panda">
<input name="animals[]" value="koala">
<input name="car[make]" value="Honda">
<input name="car[origin]" value="Japan">
</form>

不想想要使用$("form").serialize():

foo=bar&hello=world&animals%5B%5D=panda&animals%5B%5D=koalacar&%5Bmake%5D=Honda&car%5Borigin%5D=Japan

相反,我想要这个:

{"foo":"bar", "hello":"world", "animals":["panda", "koala"], "car":{"make":"Honda", "origin":"Japan"}}

据我了解,jQuery 曾经这样做过,但他们切换了 serialize 方法以返回 GET 样式的查询字符串。有没有一种简单的方法可以获得我想要的结果?

<小时/>

编辑

我更新了原来的问题,添加了 car[make]car[origin] 示例。应该假设 foo[bar][baz]foo[bar][baz][bof] 输入也可能出现在表单上。

此外,还指定了数字索引键,例如 foo[0]=afoo[1]=bfoo[4]=c应保留 ,例如,

{ ... "foo":["a", "b", undefined, undefined, "c"] ... }

最佳答案

像老板一样将表单转换为 JSON

Github:Follow along on Github

以下代码可以处理各种输入名称;并按照您的预期处理它们。

例如,

<!-- all of these will work! -->
<input name="honey[badger]" value="a">
<input name="wombat[]" value="b">
<input name="hello[panda][]" value="c">
<input name="animals[0][name]" value="d">
<input name="animals[0][breed]" value="e">
<input name="crazy[1][][wonky]" value="f">
<input name="dream[as][vividly][as][you][can]" value="g">
// output
{
"honey":{
"badger":"a"
},
"wombat":["b"],
"hello":{
"panda":["c"]
},
"animals":[
{
"name":"d",
"breed":"e"
}
],
"crazy":[
null,
[
{"wonky":"f"}
]
],
"dream":{
"as":{
"vividly":{
"as":{
"you":{
"can":"g"
}
}
}
}
}
}

用法

$('#my-form').serializeObject();

巫术

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

var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};


this.build = function(base, key, value){
base[key] = value;
return base;
};

this.push_counter = function(key){
if(push_counters[key] === undefined){
push_counters[key] = 0;
}
return push_counters[key]++;
};

$.each($(this).serializeArray(), function(){

// skip invalid keys
if(!patterns.validate.test(this.name)){
return;
}

var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;

while((k = keys.pop()) !== undefined){

// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');

// push
if(k.match(patterns.push)){
merge = self.build([], self.push_counter(reverse_key), merge);
}

// fixed
else if(k.match(patterns.fixed)){
merge = self.build([], k, merge);
}

// named
else if(k.match(patterns.named)){
merge = self.build({}, k, merge);
}
}

json = $.extend(true, json, merge);
});

return json;
};
})(jQuery);

关于jquery - 如何(完全)将查询字符串转换为 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8330126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com