Search code examples
phpjsonorientdb

how to get elements from this JSON in php


How can i get the values of the field password from this json in php

[  
   {  
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{  
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"[email protected]"
      }
   }
]

this is my code

$json = '[  
   {  
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{  
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"[email protected]"
      }
   }
]';

$json = json_decode($json,true);

echo $json[0]->oData->Name;

I am getting this error

Notice: Trying to get property of non-object


Solution

  • I see that after the json_decode() step, the properties are not protected anymore :

    $json_data = '[
        {
            "rid":"#145:0",
            "version":1,
            "oClass":"Login",
            "oData":{
                "Password":"hacker007",
                "role":null,
                "Name":"Nijeesh Joshy",
                "Email":"[email protected]"
            }
        }
    ]';
    
    $data = json_decode($json_data);
    

    So, you could access the data this way :

    $array['name'] = $data[0]->oData->Name;
    $array['password'] = $data[0]->oData->Password;
    
    var_dump($array);
    

    Output :

    array(2) { 
        ["password"]=> string(9) "hacker007" 
        ["name"]=> string(13) "Nijeesh Joshy" 
    }
    

    note :

    The classes used to build the original data array must give you methods to get the data in a proper way.