Rather than keeping your fingers crossed that your output data does not contain anything that would cause the JSON parser to barf up, consider this method based on HTTP RFC parameter parsing. The RFC RFC (2616) states the following rules:
- All fields are separated by &
- All field names are before an =, values after =, value is optional
- [] denotes "one more element to this as an array",
They also tentatively suggest the following rule, which I will offer you a choice on:
- A parameter without [] overwrites its previous versions if submitted (this is not followed by all webservers and is the matter of HTTP fragmentation/pollution attacks, by the way)
We're going to parse following this exact structure, assuming that stuff has been properly character-encoded. The start of the code should look like this:
var myObj = {};
var k = myPostbackContent.split("&");
for (var i = 0; i < k.length; i++) {
var kinfo = k[i].split("=");
var key = kinfo[0];
if (kinfo[1] !== undefined) {
var value = kinfo[1];
};
if (key.substr(-2) == "[]") {
key = key.substr(0,key.length-2);
if (myObj[key] === undefined) myObj[key] = [];
if (myObj[key] instanceof Array) myObj[key].push(value);
}
else {
The following part is dependent on your assumptions:
If you would like your elements to overwrite each other, put in the else
the following version:
myObj[key] = value;
If, instead, you would prefer to have the first instance of an element have precedence, put the following:
if (myObj[key] === undefined) myObj[key] = value;
If, like IIS, you'd prefer to have the element auto-append to a string separated by ,
, use the following:
if (myObj[key].length) myObj[key] += ",";
myObj[key] += value;
I've built a little TinkerIO script to show you how all three works. If this is not what you were looking for, do let me know. The default behaviour is "overwrite", by the way.
This method can be applied in reverse to go from an object to an URI-encoded string, by the way. Just loop through your object's properties and go by key=value, joining all the elements with a &.