2016-04-12 7 views
1

J'itérer sur JSON objetPourquoi LUCRATIF dans de arg 'retourne boucle lorsque la boucle est vide

Ma structure JSON est quelque chose comme ça

{ "someinfo": { "Paramètre": { "ABC": "123", "xyz": "456"}}}

for (var tempVal in jsonObj.someinfo.Parameter) { 
//print tempval 

} 

boucle ci-dessus renverra les valeurs correctes quand 'paramètre' dans JSON est rempli.

Si elle est vide, il imprimera arg

vide 'paramètre' dans JSON ressembleront:

{ "someinfo": { "Paramètre": ""}}}

pour imprimer les valeurs correctes ou non à vide vide est-il possible en boucle en pour-

+0

Parlez-vous de la condition «si»? – Rayon

+0

Je dirais que votre paramètre json est incorrect. Ce devrait être un objet ou null. Pas d'objet ou de chaîne vide. – RvdK

+0

Ok. Je n'ai aucun contrôle sur le contenu ou le format du fichier JSON. Donc, dans les conditions ci-dessus, que peut-on faire de mieux? –

Répondre

1

rempli Parameter est un object vide Parameter est un string

var jsonObj1={"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}}; 
 
var jsonObj2={"someinfo":{"Parameter":""}}; 
 
alert("Full: "+typeof jsonObj1.someinfo.Parameter+" ---- Empty: "+typeof jsonObj2.someinfo.Parameter)

vous ne pouvez pas "boucle dans une chaîne" donc si vous changez votre JSON ou si vous le testez comme ceci

if (typeof jsonObj1.someinfo.Parameter==="object") { 
    for (var tempVal in jsonObj.someinfo.Parameter) { 
    //print tempval 
    } 
} else { 
    //empty 
} 
0

Vous pourriez juste vérifier si jsonObj.someinfo.Parameter est un objet comme celui-ci:

var json = {"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}}; 

if(typeof json.someinfo.Parameter === "object") { 
    for(var key in json.someinfo.Parameter) { 
    // print key 
    } 
} else { 
    // Do something when it is not an object (empty) 
}