Prasanna Raghu
Prasanna Raghu

Reputation: 2663

How to access a member of a class which is inside another object from JSON using PHP

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

Upvotes: 1

Views: 577

Answers (3)

Benjamin Cremer
Benjamin Cremer

Reputation: 4822

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;

Upvotes: 2

Ryall
Ryall

Reputation: 12281

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;

Upvotes: 3

blockhead
blockhead

Reputation: 9705

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;

Upvotes: 2

Related Questions