Skip to content
Advertisement

Parse a nested JSON in PHP

I have a nested JSON which looks likes this:

{
   "user": {
      "personal_info": {
         "name": "XYZ",
         "State": "CA",
         "pincode": "12345"
       },
       "private_info": {
          "likes": "Sushi",
          "dislikes": "Curry"
       }
   }
}

And I want to obtain the “pincode” from the given JSON, Since I am new to PHP I am facing a litte difficulty in parsing the JSON file. I have tried something like this,

$jsonarray = json_decode($response->toJson(), true);
echo $jsonarray->{'user'}->{'personal_info'}->{'pincode'};

NOte that the $response is an XML response which I am converting to JSON. An I am getting this error:

Notice: Trying to get property 'user' of non-object in /Applications/XAMPP/xamppfiles/htdocs/home/index.php on line 47

Help is appreciated

Advertisement

Answer

Since you are parsing the json to an array, you access the pincode like this:

$jsonarray['user']['personal_info']['pincode'];
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement