我有一个非常独特的问题正在尝试解决:
我有以下序列化查询字符串:
a=a2&b.c=c2&b.d.e=e2&b.d.f=f2
反序列化为以下对象对象:
{
a: "a2",
b.c: "c2",
b.d.e: "e2",
b.d.f: "f2"
}
使用以下解析器(在平面对象上效果很好!)
function parse(string){
string =
'{"' + //root
string
.replace(/&/g, '","') //replace '&' with ','
.replace(/=/g,'":"')+ //replace '=' with ':'\
'"}'; //close root
return JSON.parse(string,function(key, value){ //handle URI issues
var ret;
if(key===""){ //null key means that we have something wrong with the encoding, probably escaped shit
ret = value;
}
else{
ret = decodeURIComponent(value); //decode escaped stuff
}
return ret;
});
}
这需要解析为多维对象,表示键中的 .
表示法,如下所示:
{
a:"a2",
b:{
c: "c2",
d:{
e:"e2",
f:"f2"
}
}
}
这里的任何帮助都会很棒。我一直在尝试将其递归到过去几个小时的形状,但我的大脑已经崩溃了,解决方案中没有任何乐趣。
如果有另一种方法可以将 N 维 javascript 对象解析为 URI,然后解析回 JavaSCript 对象(两个函数),我洗耳恭听。
最佳答案
您可以序列化您的 javascript 对象并对其进行 URL 编码,请参阅类似问题的答案:Standardized way to serialize JSON to query string?
关于javascript - 将查询字符串解析为嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18651963/