Archive for September, 2009

JSON Encoding and Decoding in PHP

Wednesday, September 23rd, 2009

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
)

Do you blog?

Wednesday, September 16th, 2009

I’m curious what platform you use for managing your content?
typepad_square_logo
TypePad
wp_circle_logo
Wordpress

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