I am creating project in Yii framework. In controller i have function as-
public function actiongetCuriosityQuestionAnswer()
{
$model=new Curiosityquestion;
$json='{"questionId":1}';
$obj=json_decode($json);
$model->questionId=$obj->questionId;
$record=Curiosityquestion::model()->findByPk($model->questionId);
echo "The Question=".$record->question."</br>"."Its answer is-".$record->answer;
echo CJSON::encode($record->answer,$record->question);
}
I want to send question and answer in json format. But "CJSON::encode($record->answer,$record->question);" is sending only answer in json format. i.e. CJSON::_encode is accepting only one parameter. So how to send both question and option in json format together?
Pass your whole object to CJSON::encode, e.g.:
echo CJSON::encode($record);
If you want specific elements, pass as an an array, e.g.:
echo CJSON::encode(array('answer'=>$record->answer, 'question'=>$record->question));
In your javascript, you can access the elements as javascript objects, e.g. data['answer'] or something similar
Related
I have this complex JSON Format. I don't know Whether is this valid json format or not because the key i am looking for is not in the first two dictionaries but is there in the third dictionary ? Is this valid json format ? If so , how to do parsing in this scenario ?
As am not allowed to ask new question . I edited my old question.
At the end of the first two if blocks, if you put a return statement, that will stop the program from going to execute the Alamofire block.
I am trying to access the steamid data in a json response returned by an API, specifically the Steam API.
The responses look like this:
I've made it return json but why do I see array all over the place?
How would I access the steamid data? I'm getting a bit confused as I thought this would be json.
I'm using guzzle to get the data and converting it to json using the guzzle json() method:
Any help would be appreciated.
Thanks!
The API is indeed using JSON to send/receive , however JSON is just a string, so in order to use that data PHP must parse it, which is automatically handled by guzzle, so as soon as you get the data back it has automatically decoded the data into a usable format for yourself.
It does this using the json_encode() and json_decode() functions.
You'd be able to access the steamid with the following.
// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);
foreach($players as $player)
{
$steamId = array_get($player, 'steamid', null);
}
Using the laravel helper array_get() function is a great way of ensuring you return a sane default if the data doesn't exist as well as eliminating the need to keep doing things like isset() to avoid errors about undefined indexes, etc. http://laravel.com/docs/5.1/helpers
Alternativly not using the laravel helpers you could use something similar to below, although I'd advise you add checks to avoid the aforementioned problems.
foreach($data['response']['players'] as $player)
{
$steamId = $player['steamid'];
}
If you didn't want guzzle to automatically decode the API's JSON I believe you should just be able to call the getBody() method to return the JSON string.
$json = $response->getBody();
i am working in extjs+yii. my server side design is in yii framework and client side design is in extjs. Now from extjs i am getting output data in json format as=
{"data":[{"optionId":"","questionId":"1","isAnswer":"","option":"Aus","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"2","isAnswer":"","option":"india","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"3","isAnswer":"","option":"England","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"4","isAnswer":"","option":"Srilanka","media":"","keyword":"","mediaTypeId":"","id":null}]}
So in Yii frameowk how to access this json fields? i want to access questionId and optionId fields of this json. So can someone please help me
You have to decode the json using CJSON::decode, and then access the fields:
$var='{"data":[{"optionId":"","questionId":"1","isAnswer":"","option":"Aus","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"2","isAnswer":"","option":"india","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"3","isAnswer":"","option":"England","media":"","keyword":"","mediaTypeId":"","id":null},{"optionId":"","questionId":"4","isAnswer":"","option":"Srilanka","media":"","keyword":"","mediaTypeId":"","id":null}]}';
$decoded=CJSON::decode($var);
// now your json is stored in $decoded as an array, so you can access as follows:
echo $decoded["data"][0]["questionId"];
echo $decoded["data"][0]["optionId"];
// to loop over the elements use foreach
foreach ($decoded["data"] as $value){
echo $value["questionId"];
echo $value["optionId"];
}
Using CJSON::decode is better than relying on native json_decode, as when the native is not available CJSON::decode can still decode a json string. Also in some cases json_decode can return null for correct json strings, read here for a comparison of php json libraries.
I haven't tried much like this before, so I want to know what is the recommended route for doing what I want to do.
I'm trying out the PunchFork.com api which returns recipes in a JSON dictionary. Here's an example.
How would I go about returning the "title", "thumb", and "pf_url" for each recipe so that I can display them on the page? Currently there is a couple of selects which values are used to create the url, but I don't know what to do with that url in order to display data on the page.
If you have any questions just ask.
What language are you using to generate the webpage? Most languages have built-in mechanisms for turning a JSON string into an object that the language understands.
Here's an example that uses PHP to generate an HTML page with all of the images from the API you referenced:
$response = file_get_contents($url);
$object = json_decode($response);
// Now $object is an object with the same data represented in the JSON string,
// and you can refer to its class members accordingly:
foreach ($object->recipes as $recipe)
{
$imageUrl = $recipe->source_img;
echo '<img src="$imageUrl" />';
}
I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
From where the function is getting format variable
Does format is json mean that data given to function is json or data which will be recived is json
Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all())
How will I use that data when i get that response in jquery function
If i don't use JSON in above function then how will the input and response back will chnage
Thanks
From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept: header that requests can use to indicate the preferred Content-Type for the response. On the client, you might use xhr.setRequestHeader('accept', 'application/json') to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending on how complicated your request needs to be, you can use jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can use jQuery.parseJSON to process the json data, and that will return the same JavaScript objects.
From the urlconf, just like it says in the article right below it.
The query set will be serialized as JSON.
It will be the query set represented as either XML or JSON. python manage.py shell is your friend.
You will decode it, then iterate over it.
You'll need to find some other format to serialize it in instead.