How to go through attributes of a JSON?

Asked

Viewed 13,456 times

5

I’m trying to go through attributes of a json, I’m trying this way

for (var i = 0, length = r.length; i < length; i++) {
   for (var i2 = 0,length = r[i].lenght; i2 < length; i2++ ){
       console.log("teste"+r[i][i2]);
   }
}    

how I do it properly?

Json is coming irregular, because when the service receives a null value from the database it does not arrow the field in json

[
{
    "nome": "Victor Siqueira",
    "login": "[email protected]",
    "senha": "ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f",
    "tempoSessao": 15,
    "acesso": [
        {
            "idTela": "AA00"
        }
    ]
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "as",
    "senha": "1234",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "as2",
    "senha": "9876",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "as3",
    "senha": "9876",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "as4",
    "senha": "a123",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "as5",
    "senha": "54d5cb2d332dbdb4850293caae4559ce88b65163f1ea5d4e4b3ac49d772ded14",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "login": "PFernandes",
    "senha": "54d5cb2d332dbdb4850293caae4559ce88b65163f1ea5d4e4b3ac49d772ded14",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
},
{
    "nome": "",
    "tempoSessao": 0,
    "acesso": []
}

]

  • How’s your json file? Post here for us to see.

  • ta posted diego

1 answer

2


I think the best way is for you to work with objects.

If you assign your JSON string to an object you can easily access it.

var arrayJson = JSON.parse("tua string JSON");
arrayJson.forEach(function(pessoa){
  var acesso = pessoa.acesso;
  acesso.forEach(function(acesso)){
    if (acesso != null)
      //acesso.idTela - para acessar a propriedade pelo nome
  }
})

I don’t know if I was clear, but I’ll answer any questions.

  • Ahh got it, vlw man

  • You can also use the for the same way, I’m not sure but I think the for is more performatic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.