views:

68

answers:

3

I have a JSON String like this

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

I want to access the status code in the function. this is what i tried:

$responseObj=jsonService->decode($test);//this converts the string into an Object

echo $responseObj->status->code;

now this isnt working. Can someone point me in the right direction. I think that

$responseObj->status->code

is the wrong syntax to use. What is the right syntax. I am using PHP 5.1.6 , this doesnt have the inbuilt json_decode function. So I am using a third party Class to convert. I use the following third party class

+1  A: 

Not sure what you're jsonService is doing but this worked for me:

$json = '{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

$result = json_decode($json);

echo $result->status->code;
blockhead
+3  A: 

You can use json_decode() for this task. Also, your input string should have quotes:

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

$responseObj = json_decode($test);

echo $responseObj->status->code;
Nat Ryall
+1  A: 

You should give PHP's json_decode() a try:

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';
$responseObj = json_decode($test);
echo $responseObj->status->code;

For PEARS's Services_JSON Class (Documentation):

// create a new instance of Services_JSON
$jsonService = new Services_JSON();

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';
$jsonService->decode($test);
echo $responseObj->status->code;
Benjamin Cremer
@blockhead,@kelix,@crem0r: json_decode is a fairly new function. It isnt available on PHP 5.1.6 so have to use a third party class for the JSON decode and encode.
Saeros
Well can you tell us the library you are using and any errors that come up? You're syntax is now correct from what I can see so it's likely something internal.
Nat Ryall
i have edited the question to include the name of the package and other details about the class.
Saeros
If your host is still using PHP 5.1.6 you might have bigger problems!
blockhead
Try swapping 'echo $responseObj->status->code;' for 'echo var_dump($responseObj);' to see if there are any contents returned.
Nat Ryall
@Kelix: var_dump dont need to be echoed. It outputs its result directly.
Benjamin Cremer