Jump to: navigation, search

PHP JSON Convert to Object

From w3cyberlearnings

Contents

PHP JSON to Object

JSON converts to object is similar to JSON converts to an array. You use the json_decode() function to convert JSON data to object.

Sytax

json_decode($json_data);

Example 1

<?php

$my_name = '{"age":30,"address":"huntsville"}';

$my_profile = json_decode($my_name);
print_r($my_profile);
?>

Output

stdClass Object ( [age] => 30 [address] => huntsville )

Example 2

<?php

$name = '[
	    {"name":"John"},
	    {"name":"Mark"},
	    {"name":"Marry"}
         ]';

$obj_name = json_decode($name);
print_r($obj_name);
?>

Output


Array
(
    [0] => stdClass Object
        (
            [name] => John
        )

    [1] => stdClass Object
        (
            [name] => Mark
        )

    [2] => stdClass Object
        (
            [name] => Marry
        )

)

Example 3

<?php

$my_profile = '{
		"name": "paul",
		"address": {
			"city": "houston",
		        "state": "tx",
			"apt": "244"
		 },
		"experinece":"php",
		"hobby":{
			"fishing":{"area1":"lake","area2":"sea"},
			"game":{"game1":"angry bird","game2":"angry dog"}
                 }
	}';

$my_array = json_decode($my_profile);
print_r($my_array);
?>

Output

stdClass Object
(
    [name] => paul
    [address] => stdClass Object
        (
            [city] => houston
            [state] => tx
            [apt] => 244
        )

    [experinece] => php
    [hobby] => stdClass Object
        (
            [fishing] => stdClass Object
                (
                    [area1] => lake
                    [area2] => sea
                )

            [game] => stdClass Object
                (
                    [game1] => angry bird
                    [game2] => angry dog
                )

        )

)

Related Links


--PHP JSON Convert to Array-- PHP JSON Convert to Object-- PHP Access JSON Data--

Navigation
Web
SQL
MISC
References