Share JSON Encoding and Decoding in PHP

September 23rd, 2009 by Erik

PHP Logo JSON (also known as JavaScript Object Notation) is a handy way to serialize data for passing through mediums that do not recognized complex data types – such as HTTP. While using it to pass data today I was bit by a gotcha in how associative array data is encoded and decoded.

<?php 
$associative_array = array("key1"=>"value1","key2"=>"value2");
$regular_array = array("value1","value2");
$class_object = (object) array("key1"=>"value1","key2"=>"value2");
 
// The original data
print_r($associative_array);
print_r($regular_array);
print_r($class_object);
 
// Just encode the data
print "assoc: " . json_encode($associative_array) . "\n";
print "array: " . json_encode($regular_array) . "\n";
print "class: " . json_encode($class_object) . "\n";
 
// Encode and decode the data
print_r(json_decode(json_encode($associative_array)));
print_r(json_decode(json_encode($regular_array)));
print_r(json_decode(json_encode($class_object)));
?>

Notice when we run this, the first two print_r() calls correctly return an array and the third returns an stdClass Object. Now look at the last three lines. Notice how the associative array and the stdClass Object both return the same JSON? Now look at the third set of print_r() calls. You can see the associative array data has been converted to a stdClass.

// The original data
Array
(
    [key1] => value1
    [key2] => value2
)
Array
(
    [0] => value1
    [1] => value2
)
stdClass Object
(
    [key1] => value1
    [key2] => value2
)
 
// Encoded for JSON
assoc: {"key1":"value1","key2":"value2"}
array: ["value1","value2"]
class: {"key1":"value1","key2":"value2"}
 
// Encoded and Decoded
stdClass Object
(
    [key1] => value1
    [key2] => value2
)
Array
(
    [0] => value1
    [1] => value2
)
stdClass Object
(
    [key1] => value1
    [key2] => value2
)

To avoid this behavior, simply cast the stdClass object to an array when you are decoding it. Cheers!

$json_data = '{"key1":"value1","key2":"value2"}';
$associative_array = (array) json_decode($json_data);
print_r($associative_array);
Array
(
    [key1] => value1
    [key2] => value2
)

EDIT: You can also pass in an optional parameter to json_decode() to create an associative array instead of casting with (array). The following code is functionally equivalent.

$associative_array = (array) json_decode($json_data);
$associative_array = json_decode($json_data, true);

You should follow me on Twitter.

Tags: , ,

Not ready to comment, but still found it valuable?

Leave a Reply

© 1998-2008 AF-Design, All rights reserved.