Friday, 6 September 2013

Heroic Parsing Challenge

Heroic Parsing Challenge

I have a very unique problem that I am attempting to solve:
I have the following serialized query string:
a=a2&b.c=c2&b.d.e=e2&b.d.f=f2
Deserialized into the following object object:
{
a: "a2",
b.c: "c2",
b.d.e: "e2",
b.d.f: "f2"
}
With the following parser (which works great on flat objects!)
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;
});
}
This needs to be parsed into a multi-dimensional object, representational
of the . notation within the keys, as such:
{
a:"a2",
b:{
c: "c2",
d:{
e:"e2",
f:"f2"
}
}
}
Any help here would be amazing. I've been trying to recurse this into
shape of the past few hours, but my brain has fallen apart and there is no
joy to be had in a solution. I DO NOT need the parsing methodology
changed, other than taking into account de-flattening the object. I am not
using this for vanilla URI strings, but for a special use case. Thanks in
advanced!

No comments:

Post a Comment