Tôi đã xử lý vấn đề này gần đây: Tôi phải phân tích dữ liệu có thể chứa các đối tượng được lồng sâu đến 5 cấp. Tôi cần mã để có thể xử lý cả hai dữ liệu khá phức tạp, nhưng không thể giải mã một URI đơn giản như id=213
.
Tôi đã dành khá nhiều thời gian trên google, cố gắng tìm một giải pháp thanh lịch (bán) cho vấn đề này và câu hỏi này tiếp tục hiển thị. Vì nó nhận được 1 lượt xem/ngày (cho hoặc nhận) Tôi đã quyết định đăng giải pháp của mình ở đây, hy vọng nó sẽ giúp một ai đó ra ngoài:
function form2Json(str)
{
"use strict";
var obj,i,pt,keys,j,ev;
if (typeof form2Json.br !== 'function')
{
form2Json.br = function(repl)
{
if (repl.indexOf(']') !== -1)
{
return repl.replace(/\](.+?)(,|$)/g,function($1,$2,$3)
{
return form2Json.br($2+'}'+$3);
});
}
return repl;
};
}
str = '{"'+(str.indexOf('%') !== -1 ? decodeURI(str) : str)+'"}';
obj = str.replace(/\=/g,'":"').replace(/&/g,'","').replace(/\[/g,'":{"');
obj = JSON.parse(obj.replace(/\](.+?)(,|$)/g,function($1,$2,$3){ return form2Json.br($2+'}'+$3);}));
pt = ('&'+str).replace(/(\[|\]|\=)/g,'"$1"').replace(/\]"+/g,']').replace(/&([^\[\=]+?)(\[|\=)/g,'"&["$1]$2');
pt = (pt + '"').replace(/^"&/,'').split('&');
for (i=0;i<pt.length;i++)
{
ev = obj;
keys = pt[i].match(/(?!:(\["))([^"]+?)(?=("\]))/g);
for (j=0;j<keys.length;j++)
{
if (!ev.hasOwnProperty(keys[j]))
{
if (keys.length > (j + 1))
{
ev[keys[j]] = {};
}
else
{
ev[keys[j]] = pt[i].split('=')[1].replace(/"/g,'');
break;
}
}
ev = ev[keys[j]];
}
}
return obj;
}
Tôi đã thử nghiệm nó, với dữ liệu giống như chuỗi bên dưới (4 cấp độ sâu):
str = "id=007&name[first]=james&name[last]=bond&name[title]=agent&personalia[occupation]=spy&personalia[strength]=women&personalia[weakness]=women&tools[weapons][close][silent]=garrot&tools[weapons][medium][silent]=pistol_supressed&tools[weapons][medium][loud]=smg&tools[weapons][far][silent]=sniper&tools[movement][slow]=foot&tools[movement][far]=DBS";
nào gọn gàng trả về một đối tượng, đó, khi đi ngang qua JSON.stringify
đi ra như thế này:
{"id":"007","name":{"title":"agent","first":"james","last":"bond"},"personalia":{"weakness":"women","occupation":"spy","strength":"women"},"tools":{"movement":{"far":"DBS","slow":"foot"},"weapons":{"close":{"silent":"garrot"},"medium":{"silent":"pistol_supressed","loud":"smg"},"far":{"silent":"sniper"}}}}
Nó đi một tấm séc JSLint, khi bỏ qua khoảng trắng, .
và 01.và chấp nhận ++
. Tất cả trong tất cả, tôi muốn xem xét rằng để được chấp nhận.
jQuery.param không serialization - và câu hỏi là về nghịch đảo hoạt động. –