Consider this as a fusion of an answer and a question :)
At the moment, I am in the process of configuring my server to convert the data received from a form into JSON format, just like you...
In my scenario, the form will ultimately generate a JSON object with multiple subobjects that can have their own subobjects, leading to potential infinite recursion.
The current "solution" that I'm using feels somewhat off, but it does get the job done. The getRequestBody function takes input from req.body object in express.js, which essentially follows this structure:
{
"ridic-ulously-deep-subobject": "value",
"ridic-ulously-deep-subobject2": "value",
"ridic-ulously-deep2-subobject3": "value"
}
The HTML code being utilized is:
<form>
<input name="ridic-ulously-long-class-string" value="my value" />
</form>
And here's the JavaScript function (designed to be generic - simply supply it with a req.body object like the one above and it should return a JSON object):
function getRequestBody(reqB){
var reqBody = {};
for(var keys in reqB) {
var keyArr = keys.split('-');
switch(keyArr.length){
case 1:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
reqBody[keyArr[0]] = reqB[keys];
break;
case 2:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
reqBody[keyArr[0]][keyArr[1]] = reqB[keys];
break;
case 3:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
if(!reqBody[keyArr[0]][keyArr[1]][keyArr[2]]) reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = {};
reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = reqB[keys];
break;
case 4:
// ...
//and so on, always one line longer
}
return reqBody;
}
Although this solution covers only 5 levels of subobjects currently, there may be instances where applications require reaching seven or even ten levels. It seems like a common predicament, yet my search yielded no results within a 10-minute span, hinting at possible missing keywords or absence of a suitable solution [as of now].
Is there someone out there with enough creativity and logic to streamline this complexity, or will I have to add further clutter to accommodate up to 10 sublevels?
I believe that the performance impact might not be significant in the end, but I genuinely prefer steering clear of creating such a monstrous function :D
Enjoy experimenting!
Jascha