How To Use Cjson Encode() Decode() Namevalue()

I am working on part of a project and this phase will require me to get data

from an internet site API that is returned in JSON format.

Simple things like authentication return strings like

{"response":{"status":"OK","token":"bo516d21k73ik91d86hsnp84h7"…}

[b]

Questions:

How do I make a similar call from within Yii ?

How do I parse out and find the value of the JSON string such as "status"? [/b]

I have tried to use CJSON::nameValue() but it never works for me. The Class documentation defines it as:

array-walking function for use in generating JSON-formatted name-value pairs.

protected static string nameValue(string $name, mixed $value)

$name string name of key to use

$value mixed reference to an array element to be encoded

{return} string JSON-formatted name-value pair, like ‘“name”:value’

I think I am doing something wrong with it. Is it because it is protected?

No matter what I put in for $value it fails with no output or error, just

corrupts the output of my view file.




 $response = {"response":{"status":"OK","token":"bo516d21k73ik91d86hsnp84h7"...}

 echo  CJSON::nameValue("status", $response[0]);



I have not found much info on working with JSON and am looking for some advice and guidance.

I have played with the CJSON::encode() function with a simple model and that works well.




$model = Category::model()->findAll();

	echo  CJSON::encode($model);



Which returns:

[{"id":"1","category":"Education","create_date":"2012-09-29 23:34:21","source":"Q1Media","parent_id":null},{"id":"2","category":"Entertainment","create_date":"2012-09-29 23:34:37","source":"Q1Media","parent_id":null},…]

I have also found the array_map function to limit the data returned.




$data=array_map(create_function('$m','return $m->getAttributes(array(\'id\',\'category\'));'),$model);



It returns:

[{"id":"1","category":"Education"},{"id":"2","category":"Entertainment"}]

As always, thank you for all the assistance.

Dear Friend

We can do the things in the following way.




$jsonObject='{"response":{"status":"OK","token":"bo516d21k73ik91d86hsnp84h7"}}';

$obj=json_decode($jsonObject);

echo $obj->response->status;

echo $obj->response->token;



I hope I helped a bit.

Seenivasan - that was a huge help! Thank you !!!

One other question if I may… How to use nameValue()?

Based on what you have shown me here, I don’t know that I need it, but still want to understand it.

Thank you again!

Dear Friend

As you have already pointed out CJson::nameValue is a pretected method.

It is used inside the CJson::encode.

It is intended in making Json objects rather than parsingout json objects.

Regards.

Thank you for the clarification my friend! That makes sense based on my interpretation but I am just learning and am not confident in this new terr-Yii-tory.