Json Question

I have an interface to an API that returns a json object.

The normal response would be something like


{  "response": { "status":"OK","id":241  }}

I decode the object as follows and check to see if it is ok.




$obj = json_decode($jsonObject);

$ok = $obj->response->status;



The problem exists if there is an error.

The JSON then looks like




{ "response": { "error_id":"NOAUTH",....}}


and I would get it's error code 


$error_id = $obj->response->error_id;




If I code it to check the error it will blow up with an error from Yii as follows:

Undefined property: stdClass::$error_id

Because the error does not exist.

How best to handle this ?

Is there a Yii function to check it?

Something like isset( $obj->response->error_id ) ?

This problem is killing me, I can’t handle exceptions very gracefully!

Thanks for any advice!

First, as a matter of good practices, I recommend using CJSON::decode(). IIRC, Its just a wrapper to json_decode() but its a good practice to follow to use the framework classes.

Indeed probably the json you’ve got does not indicate an error, and therefore does not contain the attribute you’re checking - and there goes your explosion.

You can check the existence of this attribute right before you’re checking its value, just as you suggested - with isset() php method.

Also note that json_decode has a second parameter $assoc which is "false" by default.

So if you use json_decode($data) it will return an object, but if you use json_decode($data, true) then it will return an associative array.

And Yii’s CJSON::decode() changes this default to “true”, so CJSON::decode($data) will return an array and CJSON::decode($data, false) will return an object.

Hi,

you can try the following code.


public function actionGetBusinessList($status = 200, $body = '', $content_type = 'text/json'){

		$status_header = 'HTTP/1.1 ' . $status . ' ';

		header($status_header);

		header('Content-type: ' . $content_type);

		$res = array();

		$error =array();

		$response=array();

		$post = file_get_contents("php://input");

		$data = CJSON::decode($post, true);

		$model=new Business();

		$response=$model->GetBusinessList($data); /// your function

		header('Content-type:application/json');

		echo CJSON::encode($response);

		exit();

	}

Best Regards,

Ankit Modi

Thank you all !

Good points on the CJSON::decode() and the boolean that controls difference between an array and the object.

I recall having issues dealing with CJSON::decode() and json_decode()…that makes sense now!