I'm in trouble with a nasty JSON object that I need to convert to JS object with variable depth.
Shortly: (I'm using jQuery)
var nastyJSON_string = "{"generics_utenteID":"1","generics_elencoID":"1","mainbar_ade_stepID_0":"1","mainbar_ade_stepID_1":"3","mainbar_ade_stepTitle_0":"blablabla", "mainbar_ade_stepTitle_1" : "quiquoqua"}";
var nastyJSON = JSON.parse(nastyJSON_string);
// nastyJSON if parsed correctly now is: {generics_utenteID:"1",generics_elencoID:"1" ...and so on}.
Now, I need to convert that nastyJSON to a JS object with variable depth. I mean:
var reusableJSObject = {
generics : {
utenteID : 1,
elencoID : 1
},
mainbar : {
ade : {
stepID : {
0 : 1,
1 : 3
},
stepTitle : {
0 : "blablabla",
1 : "quiquoqua"
}
}
}
}
My best is to create it manually, looping nastyJSON, switch-casing keys and creating objects adding values at the end of the well-known depth.
Like this:
jQuery.each(nastyJSON, function(key,value){
var keysp = key.split('_');
switch(keysp[0])
{
//# generics
case 'generics':
if(!reusableJSObject.hasOwnProperty(keysp[0])) { reusableJSObject[keysp[0]] = new Object(); };
switch(keysp[1])
{
//# utenteID
case 'utenteID':
if(!reusableJSObject[keysp[0]].hasOwnProperty(keysp[1])) { reusableJSObject[keysp[0]][keysp[1]]; };
reusableJSObject[keysp[0]][keysp[1]] = Number(value);
break;
//# elencoID
case 'elencoID':
if(!reusableJSObject[keysp[0]].hasOwnProperty(keysp[1])) { reusableJSObject[keysp[0]][keysp[1]]; };
reusableJSObject[keysp[0]][keysp[1]] = Number(value);
break;
}
break;
//# mainbar
case 'mainbar':
if(!reusableJSObject.hasOwnProperty(keysp[0])) { reusableJSObject[keysp[0]] = new Object(); };
break;
//... and So On!
}
});
But, what if I do not know at first the nastyJSON structure, and I only know that nastyJSON has keys I had to split and nest until the end of the split?
Thanks in advance.
You don't need jQuery, vanilla JS will do (here is a fiddle):
var json = '{"generics_utenteID":"1","generics_elencoID":"1","mainbar_ade_stepID_0":"1","mainbar_ade_stepID_1":"3","mainbar_ade_stepTitle_0":"blablabla", "mainbar_ade_stepTitle_1" : "quiquoqua"}';
var obj = JSON.parse(json);
function parse(object) {
var result = {};
var temp = {};
var keys;
for (var property in object) {
keys = property.split('_');
temp = result;
for (var i = 0; i < keys.length - 1; i++) {
if (typeof temp[keys[i]] == 'undefined') {
temp[keys[i]] = {};
}
temp = temp[keys[i]];
};
temp[keys[i]] = object[property];
}
return result;
}
console.log(JSON.stringify(parse(obj)));
Output:
{
"generics":{
"utenteID":"1",
"elencoID":"1"
},
"mainbar":{
"ade":{
"stepID":{
"0":"1",
"1":"3"
},
"stepTitle":{
"0":"blablabla",
"1":"quiquoqua"
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With