Know the JSON object name

Asked

Viewed 691 times

4

I have a JSON and need to know the name of my object and the values it has, for example:

    {"Pessoas" :
          [ 
           {"Nome": "Welson Play", "Idade":19}, 
           {"Nome": "Stephanie", "Idade":15},
           {"Nome": "João Pedro", "Idade":17}
          ] 
    }

I needed to pick up the code the name Pessoas and the values that each person has, but that without knowing the name, for example, could be Animais, Carros. This due to my table on BD the columns may vary, ie navigate by JSON.

  • 1

    Do you want the solution in PHP? I think I answered wrong in javascript. =(

  • Hi @Fernando thanks for answering, can be in PHP tbm, I need to analyze the codes and see which one I will use, if you can help me with PHP I appreciate

  • Ok! I will remove my answer, PHP not very much to mine, hehe. And I think Sergio has already responded well in PHP. I didn’t notice the tags before I answered, sorry!

1 answer

3


You can use a foreach to iterate this object.

For example:

$jsonstring = '{"Pessoas" :
      [ 
       {"Nome": "Welson Play", "Idade":19}, 
       {"Nome": "Stephanie", "Idade":15},
       {"Nome": "João Pedro", "Idade":17}
      ] 
}';

$obj = json_decode($jsonstring);

foreach($obj as $chave => $array) {
    echo $chave;    // dá "Pessoas"
    // fazer aqui o que fôr preciso com a array $array
}

Example: https://ideone.com/u6kmv8

To read objects children objects, (nome, idade ....) you need to continue iterating. In the example above you can iterate the array and then the keys/value of each object.

In practice it takes two more loops:

foreach($obj as $chave => $array) {
    foreach($array as $index => $pessoa) {
        foreach($pessoa as $dado => $valor) {
            // neste nível estás dentro de cada objeto `{"Nome": "João Pedro", "Idade":17}` 
  • 3

    You answered first... kkkk

  • @Sergio, how would I read the objects children, (name, age ....)?

  • @Furlan added more info to the answer. If you can’t implement I need a concrete example of how you want to use these values within each person’s object.

  • @Sergio, to really iterate for all children I find it more interesting to use recursiveness, but it really depends on how the AP intends to use this. But overall and comprehensive recursiveness is the solution.

  • 2

    @Fernando agree. The question is unclear in what to do with the data, hence using 3 equal foreach already opening port to be more DRY/recursive.

  • Thank you all, @Sergio thanks for your time, again case closed!

  • @Sergio, I can catch the characteristic of the object without knowing, example, my object has 3 characteristics: name, age, sex. But you can vary those 3, there in the 3rd foreach I put dynamically?

Show 2 more comments

Browser other questions tagged

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