开发者

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

开发者 https://www.devze.com 2022-12-11 11:30 出处:网络
I have a JSON String like this $test=\'{\"var1\":null,\"var3\":null,\"status\":{\"code\":150,\"message\":\"b开发者_Python百科lah blah\"}}\';

I have a JSON String like this

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"b开发者_Python百科lah 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

  • @package Services_JSON
  • @author Michal Migurski
  • @author Matt Knapp
  • @author Brett Stimmerman
  • @copyright 2005 Michal Migurski
  • @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
  • @license http://www.opensource.org/licenses/bsd-license.php
  • @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198


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;


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;


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消