emailconfirmed, nsInternRO, nsInternRW, Administrators
3,356
edits
(Created page with '== JSON Introduction == <p><strong>JSON</strong> (acronym for JavaScript Object Notation) is a data interchange format, designed for human-readability. It's lightweight, te…') |
mNo edit summary |
||
| (30 intermediate revisions by 2 users not shown) | |||
| Line 1: | Line 1: | ||
This article has been created by Luís Filipe Couto (thanks!). Please feel free to add or correct. | |||
There's also an article here: [[IFD:WApplications/Vortraege/APIs_JSON]] | |||
I'm assuming that you are familiar with [[HTML]], [[CSS]], [[JavaScript]] and [[PHP]] for this article. | |||
== JSON Introduction == | == JSON Introduction == | ||
| Line 48: | Line 53: | ||
<sub>However, like Javascript, JSON can be formatted to be single-line.</sub> | <sub>However, like Javascript, JSON can be formatted to be single-line.</sub> | ||
==Pratical Examples with [[JavaScript]]== | |||
===Fetch and Include JSON File=== | |||
<p>I will show now, how to use [[JavaScript]] to print JSON files on a [[HTML]] page. I will use the [ | <p>I will show now, how to use [[JavaScript]] to print JSON files on a [[HTML]] page. I will use the [http://web.uni-weimar.de/medien/wiki/JSON#Twitter_API_Introduction Twitter API] to get a JSON file.</p> | ||
[http://twitter.com/statuses/public_timeline.json http://twitter.com/statuses/public_timeline.json] this link allow us to download a JSON file with the last 20 public tweets on [http://www.twitter.com Twitter]. Due security reasons [http://en.wikipedia.org/wiki/Cross-site_scripting (XSS)], we can not fetch the file with using XmlHttpRequest ([[AJAX]]) directly as so, we include it directly in the HTML page: | [http://twitter.com/statuses/public_timeline.json http://twitter.com/statuses/public_timeline.json] this link allow us to download a JSON file with the last 20 public tweets on [http://www.twitter.com Twitter]. Due security reasons [http://en.wikipedia.org/wiki/Cross-site_scripting (XSS)], we can not fetch the file with using XmlHttpRequest ([[AJAX]]) directly as so, we include it directly in the HTML page: | ||
| Line 100: | Line 105: | ||
</source> | </source> | ||
<p>Because JSON is natively Javascript we don't need to parse it, in this particular example, and we can itinerate it's values directly using the dot syntax.</p> | <p>Because JSON is natively Javascript we don't need to parse it, in this particular example, and we can itinerate it's values directly using the dot syntax.</p> | ||
==Twitter== | ---- | ||
===Create a JSON Object=== | |||
So far we saw how to fetch and include an external JSON File and how to iterate and print a JSON object, but how do we create a JSON of our own? Since JSON was originally made from Javascript, to create an JSON all we need to do, it's to declare it: | |||
<source lang="javascript"> | |||
var jsonObject = { | |||
name: 'Luís', | |||
age: 23, | |||
student: true, | |||
hobbies: ['Reading', 'Sleeping', 'Procrastinating'], | |||
family_members: [ | |||
{name: "Manuel", age: 50, relation: "father"}, | |||
{name: "Maria", age: 47, relation "mother"} | |||
] | |||
}; | |||
alert(jsonObject.family_members[0].relation); //returns "father" | |||
</source> | |||
==Pratical Examples with PHP== | |||
===Create and Decode a JSON Object=== | |||
<p>[[PHP]] natively supports JSON which makes this process a no-effort task! So to create a JSON Object, we first define an array and populate it, then we encode the array to JSON:</p> | |||
<source lang="PHP"> | |||
<?php | |||
$myTweet = array( | |||
"user" =>array( | |||
"id" => 123456, | |||
"name" => Username), | |||
"text" => "I'm going to be inside a JSON", | |||
"created_at" => "Wed Jul 07 18:12:12 +0000 2010" | |||
); | |||
$myJSONTweet = json_encode($myTweet); | |||
$myTweets = json_decode($myJSONTweet, true); //if true it will decode to an associative array | |||
?> | |||
</source> | |||
<p>The <em><strong>json_encode()</strong></em> function actually takes care of the JSON syntax, and even makes the object <em>"user"</em> inside the JSON. To decode it, we just use the <em><strong>json_decode()</strong></em> and the PHP will transform the JSON into an associative array, pretty much the opposite of the json_encode().</p> | |||
==Twitter API Introduction== | |||
<blockquote cite="http://twitter.com/about">"Twitter is a real-time information network powered by people all around the world that lets you share and discover what’s happening now. | |||
Twitter asks “what’s happening” and makes the answer spread across the globe to millions, immediately."<br /><em>in [http://twitter.com/about Twitter About Us page]</em></blockquote> | |||
<blockquote cite="http://www.slideshare.net/padday/the-real-life-social-network-v2">The social web is not a fad, and itʼs not going away. Itʼs not an add-on to the web as we know it today. Itʼs a fundamental change, a re-architecture, and in hindsight its evolution is obvious. | |||
Make no mistake about this. Everyone in this room will need to learn how to design social features on websites. Whether you like it or not<br /><em>in [http://www.slideshare.net/padday/the-real-life-social-network-v2 Paul Adams in The Real Social Network]</em></blockquote> | |||
<p>An <strong>API</strong> (Application Programming Interface) it's a interface implemented by a service that allows programmers to interact with other software</p> | |||
<p>When used in the context of web development, an API is typically a defined set of Hypertext Transfer Protocol (HTTP) request messages, along with a response message, usually in a Markup Language (like [[XML]]) or JSON, other formats that are also quite common are RSS and ATOM</p> | |||
<p>The use of API's, allowed web services to share content and create an open sharing arquitecture. A common example it's the video embedding through [http://www.youtube.com YouTube] or [http://www.vimeo.com Vimeo]</p> | |||
<p>My choice of using the Twitter API, is due to two reasons: | |||
<ul> | |||
<li>It's relatively easy, and pretty straightforward to use</li> | |||
<li>It's well documented</li> | |||
</ul> | |||
</p> | |||
---- | |||
===What you need to know=== | |||
<p>Among several things, i believe that these three are essential to use the Twitter's API: | |||
<ul> | |||
<li>The API is entirely HTTP-based | |||
<ul><li>Where methods to retrieve data use the GET request.</li> | |||
<li>publishing, modifying or destroying data on Twitter requires the POST request.</li></ul> | |||
<li>A command-line is all you need to interact with the Twitter API</li> | |||
<li>There are [http://dev.twitter.com/pages/libraries Twitter API libraries] for almost any language</li></ul></p> | |||
==Create a Small Twitter Client== | |||
<p>Since it's so easy to use the Twitter's API, i'm going to show here how to create a small twitter client. I'm going to do some extra steps so that i can refer a few more things about JSON and Twitter</p> | |||
<p>So the process i'm going to use is:</p> | |||
<ol> | |||
<li>[[#Get the JSON File with PHP and cURL]]</li> | |||
<li>[[#Print the tweets]]</li> | |||
<li>[[#Serialize a form with JavaScript]]</li> | |||
<li>[[#Send the form to PHP with AJAX]]</li> | |||
<li>[[#Post the tweet using a PHP Twitter Library]] | |||
</ol> | |||
---- | |||
===Get the JSON with [[PHP]] and [[cURL]]=== | |||
<source lang="PHP" > | |||
<?php | |||
$user = 'username'; | |||
$password = 'password'; | |||
$ch = curl_init("http://api.twitter.com/1/statuses/home_timeline.json?count=3"); | |||
curl_setopt($ch,CURLOPT_TIMEOUT, 30); | |||
curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); | |||
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); | |||
$result=curl_exec ($ch); | |||
?> | |||
</source> | |||
<p>The ability to use [http://curl.haxx.se/ cURL], is what allows us to interact with Twitter with the command-line, the same commands exist in PHP and we're using them right now to fetch the JSON. | |||
---- | |||
===Print the Tweets=== | |||
<source lang="PHP" highlight="14-20"> | |||
<?php | |||
$user = 'username'; | |||
$password = 'password'; | |||
$ch = curl_init("http://api.twitter.com/1/statuses/home_timeline.json?count=3"); | |||
curl_setopt($ch,CURLOPT_TIMEOUT, 30); | |||
curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); | |||
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); | |||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); | |||
$result=curl_exec ($ch); | |||
$resultado = json_decode($result, true); | |||
foreach ($resultado as $value) { | |||
echo $value["user"]["name"]; | |||
echo $value["text"]; | |||
echo $value["created_at"]; | |||
} | |||
?> | |||
</source> | |||
In the hightlighted area we decode the json into an array and then iterate and print the values of that array, with a little bit of CSS we can achieve something like this:</p> | |||
[[File:Screen_shot_2010-07-07_at_7.24.39_PM.png]] | |||
---- | |||
===Serialize a form with [[JavaScript]]=== | |||
<p>This is the part, where i want to show a few more things about JSON which is the JSON Parsers. JSON usually travels between web app and the server as a string, javascript has a really nice (and dangerous!) function which is <em><strong>eval()</strong></em> this function reads string values and interprets it as javascript, which is quite convenient if the JSON file comes from a secure source, however we can't assure the security of an external service like twitter, so i'm going to use a parser to convert the values of our form into a JSON, while i'm also going to show the opposite, convert a JSON into a Javascript Object with the parser</p> | |||
<sub>To save a few lines i'll be using the [http://www.jquery.com jQuery Framework]</sub> | |||
<source lang="javascript"> | |||
<form action="sendTweet.php" method="post" accept-charset="utf-8"> | |||
<input type="text" name="username" value="" id="username"> | |||
<input type="pasword" name="password" value="" id="password"> | |||
<textarea name="tweet" value="tweet"></textarea> | |||
<p><input type="submit" id="submit" value="Continue →"></p> | |||
</form> | |||
<script type="text/javascript" charset="utf-8" src="json2.js"></script> | |||
<script type="text/javascript" charset="utf-8" src="jquery-1.4.2.min.js"></script> | |||
<script type="text/javascript" charset="utf-8"> | |||
$(document).ready(function(){ | |||
$('form').submit(function(e){ | |||
e.preventDefault(); | |||
obj = new Object; //Going to do an object only to use the parser | |||
obj.username = $('#username').val(); | |||
obj.password = $('#password').val() | |||
obj.tweet = $('#tweet').val(); | |||
obj2string = JSON.stringify(obj); //convert object to json string | |||
}); | |||
}); | |||
</script> | |||
</source> | |||
<p>As you can see, i'm using the parser to safely convert a javascript object to a JSON String</p> | |||
---- | |||
===Send the form to PHP with AJAX=== | |||
Here i'm sending the previous JSON string to a PHP file with AJAX, and parsing the twitter answer into a javascript object. To every request, Twitter responds with a JSON, in this case, the JSON file contains the info about the tweet we posted using PHP. | |||
<source lang="javascript"> | |||
$.post("sendTweet.php",{"sendedTweet":obj2string},function(data)){ | |||
tweet = JSON.parse(data); //convert json string to object | |||
} | |||
</source> | |||
---- | |||
===Post the tweet using a [http://dev.twitter.com/pages/libraries PHP Twitter Library]=== | |||
<p>On the other side in PHP, we get the values, and we use a PHP Library to send the tweet, libraries change according to its programmer, so it's always a good idea to read the instructions.</p> | |||
<p>On the other hand, if you don't want to use a library you can always use the cURL method showed above to do an authenticated post</p> | |||
<source lang="php"> | |||
<?php | |||
//Currently using the Tijs Verkoyen library http://classes.verkoyen.eu/twitter/ | |||
if(isset($_POST['sendedTweet'])){ | |||
$tweet = json_decode($_POST['sendedTweet']); #decode the JSON string | |||
$username = $tweet['username']; | |||
$password = $tweet['password']; | |||
$tweet = $tweet['tweet']; | |||
include "twitter_library.php"; | |||
$twi_user = new Twitter("$username","$password"); | |||
$user_text = $tweet; | |||
$twi_user->updateStatus($user_text); | |||
echo $twi_user | |||
} | |||
?> | |||
</source> | |||
<p>And that's pretty much it. I hope i was able to make myself clear during this article, however if you have any doubt please feel free to contact me to [mailto:lcouto87@gmail.com here]</p> | |||
==Resources== | |||
* [http://www.json.org JSON Official Website] | |||
* [http://www.twitter.com Twitter.com] | |||
* [http://dev.twitter.com Twitter Developer Page] | |||
* [http://www.php.net PHP.net] | |||
* [http://www.jquery.com jQuery.com] | |||
--[[User:Couto|Couto]] 21:07, 7 July 2010 (UTC) | |||
[[Category:Javascript]] | |||
[[Category:Netztechnik]] | |||
[[Category:Programmiersprachen]] | |||
[[Category:Software]] | |||
[[Category:Webtechnologien]] | |||
[[Category:Louis Couto]] | |||