user12897573
user12897573

Reputation:

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

Upvotes: 0

Views: 198

Answers (2)

Umair Khan
Umair Khan

Reputation: 1752

json_decode

Takes a JSON encoded string and converts it into a PHP variable.

The decoded result can be object or associative arrays as per value of second parameter of json_decode.

Code:

$json = '{
"user": {
    "personal_info": {
        "name": "XYZ",
        "State": "CA",
        "pincode": "12345"
    },
    "private_info": {
        "likes": "Sushi",
        "dislikes": "Curry"
    }
}
}';
echo 'As Object' . PHP_EOL;
$resObj = json_decode($json);
var_dump($resObj, $resObj->user->personal_info->pincode);
echo PHP_EOL . PHP_EOL . 'As Associative Array' . PHP_EOL;
$resObj = json_decode($json, true);
var_dump($resObj, $resObj['user']['personal_info']['pincode']);

Output:

As Object
/var/www/html/test.php:34:
object(stdClass)[56]
  public 'user' => 
    object(stdClass)[50]
      public 'personal_info' => 
        object(stdClass)[44]
          public 'name' => string 'XYZ' (length=3)
          public 'State' => string 'CA' (length=2)
          public 'pincode' => string '12345' (length=5)
      public 'private_info' => 
        object(stdClass)[51]
          public 'likes' => string 'Sushi' (length=5)
          public 'dislikes' => string 'Curry' (length=5)
/var/www/html/test.php:34:string '12345' (length=5)


As Associative Array
/var/www/html/test.php:37:
array (size=1)
  'user' => 
    array (size=2)
      'personal_info' => 
        array (size=3)
          'name' => string 'XYZ' (length=3)
          'State' => string 'CA' (length=2)
          'pincode' => string '12345' (length=5)
      'private_info' => 
        array (size=2)
          'likes' => string 'Sushi' (length=5)
          'dislikes' => string 'Curry' (length=5)
/var/www/html/test.php:37:string '12345' (length=5)

Working Example

Upvotes: 0

catcon
catcon

Reputation: 1363

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

$jsonarray['user']['personal_info']['pincode'];

Upvotes: 2

Related Questions