How do I turn an api link into something useful? - json

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" />';
}

Related

perl decode and encode json preserving order

I have in a text database field a json encoded chart configuration in the form of:
{"Name":[[1,1],[1,2],[2,1]],"Name2":[[3,2]]}
The first number of these IDs is a primary key of another table. I'd like to remove those entries with a trigger when the row is deleted, a plperl function would be good except it does not preserve the order of the hash and the order is important in this project. What can I do (without changing the format of the json encoded config)? Note: the chart name can contain any characters so it's hard to do it with regex.
You need to use a streaming JSON decoder, such as JSON::Streaming::Reader. You could then store your JSON as an array of key/value pairs, instead of a hash.
The actual implementation of how you might use do this is highly dependent on the structure of your data, but given the simple example provided... here's a simple implementation.
use strict;
use warnings;
use JSON::Streaming::Reader;
use JSON 'to_json';
my $s = '{"Name":[[1,1],[1,2],[2,1]],"Name2":[[3,2]]}';
my $jsonr = JSON::Streaming::Reader->for_string($s);
my #data;
while (my $token = $jsonr->get_token) {
my ($key, $value) = #$token;
if ($key eq 'start_property') {
push #data, { $value => $jsonr->slurp };
}
}
print to_json(\#data);
The output for this script is always: -
[{"Name":[[1,1],[1,2],[2,1]]},{"Name2":[[3,2]]}]
Well, I managed to solve my problem, but it's not a general solution so it will probably not help the casual reader. Anyway I got the order of keys using the help of the database, I called my function like this:
SELECT remove_from_chart(
chart_config,
array(select * from json_object_keys(chart_config::json)),
id);
then I walked through the keys in the order of the second parameter and put the results in a new tied (IxHash) hash and json encoded it.
It's pretty sad that there is no perl json decoder that could preserve the key order when everything else I work with, at least on this project, does it (php, postgres, firefox, chrome).
JSON objects are unordered. You will have to encode the desired order into your data somehow
{"Name":[[1,1],[1,2],[2,1]],"Name2":[[3,2]], "__order__":["Name","Name2"]}
[{"Name":[[1,1],[1,2],[2,1]]},{"Name2":[[3,2]]}]
May be you want streaming decoder of JSON data like SAX parser. If so then see JSON::Streaming::Reader, or JSON::SL.

Perl converting GET to POST

I have built a web application that passes all form input data through the URL. Can someone help me figure out how to send data using POST instead? I am starting to handle large amounts of data, and GET creates an issue with the URL being too long. If there is a simple JavaScript way to do this, I'd be interested as well.
For example, the input form has an attribute called txtName and the user has typed John. On the new form, I need it to get John and assign it to the variable $Name using the POST method.
Right now I'm using GET and am chomping the parameters to get the data out of the URL.
How do you, in Perl, get POST to work on both forms?
I changed GET to POST on the form submitting data. On the form receiving data I put
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
$ua = LWP::UserAgent->new;
at the top, then under that I put
my req = POST 'http://intranet/webservice/enhancements/ManagementEnhancementPerson.pl',
[ $Person ='person' ];
The web page is the page I'm taking data from, $Person is the variable I want it to be, and person is the name of the input on the original form.
I've been stuck on this for a while. I'm relatively new to Perl and web development.
Here are my use statements at the top of the page receiving the data.
use CGI::Carp 'fatalsToBrowser';
use warnings;
use Net::SMTP;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
$ua = LWP::UserAgent->new;
If you make the request using the following (slightly altered from what you posted to make sense):
my $request = POST 'http://.../ManagementEnhancementPerson.pl', [
person => $Person,
];
my $response = $ua->request($request);
You would extract the value using the following in ManagementEnhancementPerson.pl:
use CGI qw( );
my $cgi = CGI->new;
my $Person = $cgi->param('person');
The CGI module provides the form data via param regardless of whether the form was submitted using GET or POST.

How to access multiple value json elements in yii framework

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.

How to send multiple records in json format

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

I'm looking for a viewer which can display the exported JSON(PHP Style) data out of any Drupal View?

As you all know there is an Export "Button" when you Click(in Drupal) on your View(e.g. Customer Data etc.). So I'd like to visualize somehow the data I geht here(which is unfortunately JSON Objects in PHP Style). Most Viewers & Readers (e.g. this here http://jsonviewer.stack.hu/ or some other SW solutions) can't read this Type of JSON!
I'm aware of the possibility of parsing this Exported JSON Data in php but I'm lookin for a more friendly solution.
Thanxx out there!
George
It's not 'PHP style JSON' (I'm quite sure such a thing doesn't exist) it's a PHP array!
Either grab the views datasource module which can export views as JSON/XML natively, or simply run the PHP output through json_encode().
If the output looks like this:
$view = array(
'something' => 'something',
...
);
Then you need to run $string = json_encode($view); echo $string;.
That will output the View as a JSON object/array :-)