{
"field-one" : 1,
"field-two" : 2,
"field-three" : [ 1, 2, 3 ]
}
Most JSON libraries should convert this JSON string into a native object with ease. However, in PHP when you try to access $obj->field-one directly, PHP will complain given the hyphen in the member name. The solution to this simple problem, is to wrap the name in curly braces, like so:
$obj->{'field-one'}
Here's a more complete example using Services_JSON in PHP:
<?php
require_once("JSON.php");
$json = new Services_JSON();
$string = "{\"field-one\":1,\"field-two\":2," .
"\"field-three\":[1,2,3]}";
$obj = $json->decode( $string );
// Will FAIL
//echo $obj->field-one;
// WORKS
echo $obj->{'field-one'};
?>
For your download convenience, you can find the latest Services_JSON library here (as of 4/22/09). The official PEAR CVS repository for Services_JSON can be found here. Enjoy.


Did you find this post helpful, or at least, interesting?