Sono in difficoltà con un brutto oggetto JSON che ho bisogno di convertire in oggetto JS con profondità variabile.Creare dinamicamente oggetti JavaScript con profondità variabile
Poco: (sto usando 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}.
Ora, ho bisogno di convertire che nastyJSON a un oggetto JS con profondità variabile. Intendo:
var reusableJSObject = {
generics : {
utenteID : 1,
elencoID : 1
},
mainbar : {
ade : {
stepID : {
0 : 1,
1 : 3
},
stepTitle : {
0 : "blablabla",
1 : "quiquoqua"
}
}
}
}
mio migliore è creare manualmente annodare chiavi nastyJSON, passare rivestimento e creazione di oggetti aggiungendo valori alla fine della profondità noto.
Ti piace questa:
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!
}
});
Ma, cosa succede se non so in un primo momento la struttura nastyJSON, e so solo che nastyJSON dispone di tasti che ho dovuto dividere e nido fino alla fine della scissione?
Grazie in anticipo.
Non posso cambiare il tipo di stringa che deve essere analizzato (il nastyJSON_string). Devo lavorare con le chiavi con "_" in esse per indicare un cambio di livello nell'oggetto js finale. – Nineoclick