JSON object conversion question JSON object conversion question json json

JSON object conversion question


There's more information in this older question. The short version is that properties on PHP objects/classes follow the same naming convention as variables. A numerical property is invalid on a PHP object, so there's no clear rule as to what should happen when serializing an object from another language (json/javascript) that has a numerical key. While it seems obvious to you what should happen with the above, someone with a different bias sees PHP's behavior in this instance as perfectly valid and preferred.

So, it's kind of a bug, but more an undefined area of the spec with no clear answer, so don't expect the behavior to change to meet your liking, and if it does change, don't expect that change to be permanent.

To address some of the issues in the comments, consider this

header('Content-Type: text/plain');$json = '{"0" : "a"}';$obj = json_decode($json);$a = (array) $obj;var_dump($a);var_dump(array(0=>'a'));var_dump(array('0'=>'a'));

that will output something like this

array(1) {  ["0"]=>  string(1) "a"}array(1) {  [0]=>  string(1) "a"}array(1) {  [0]=>  string(1) "a"}

An array with a single string key zero isn't a valid PHP construct. If you try to create one PHP will turn the zero into an int for you. When you ask PHP to do a cast it doesn't have a definition for, it ends up creating an array with a string key (because of the ill defined rules around what should happen here).

While it's blatantly obvious that this is "wrong" behavior on the part of PHP, defining the right behavior in a language that's weakly typed isn't easy.


You can just access it as an object (stdClass) rather than an array:

$json = '{"0" : "a"}';$obj = json_decode($json);print_r($obj);echo("a0:".$obj->{"0"}."<br>");

This is the most straightforward since your JavaScript was an object ({}) rather than an array [] to begin with.

Alternatively, you can do this

$arr = json_decode($json, true);

The second optional parameter makes it output an associative array.http://us.php.net/json_decode


Why are you doing this? Do you know you can have the JSON decoded values as an array directly?

$arr = json_decode($json, true);echo '<pre>';print_r($arr);echo '</pre>';