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.