mNo edit summary |
mNo edit summary |
||
Line 244: | Line 244: | ||
$('form').submit(function(e){ | $('form').submit(function(e){ | ||
e.preventDefault(); | e.preventDefault(); | ||
obj = new Object; | obj = new Object; //Going to do an object only to use the parser | ||
obj.input1 = $('#lol').val(); | obj.input1 = $('#lol').val(); | ||
obj.input2 = $('#lmao').val() | obj.input2 = $('#lmao').val() | ||
obj2string = JSON.stringify(obj); //convert object to json string | obj2string = JSON.stringify(obj);//convert object to json string | ||
alert(obj2string); | alert(obj2string); | ||
$.post("sendTweet.php",obj2string,function(data)){ | $.post("sendTweet.php",obj2string,function(data)){ | ||
tweet = JSON.parse(data); //convert json string to object | tweet = JSON.parse(data);//convert json string to object | ||
} | } | ||
}); | }); |
Revision as of 20:31, 7 July 2010
First of all, i'm sorry for writing this article in english, although i've been around for a few months, i still don't feel comfortable enough to write in german. I'm assuming that you are familiar with HTML, CSS, JavaScript and PHP for this article.
JSON Introduction
JSON (acronym for JavaScript Object Notation) is a data interchange format, designed for human-readability. It's lightweight, text-based, open standard and usually serves as an alternative to XML to transmit data over a network or between a server and a web application.
JSON was a subset of the JavaScript programming language, but despite its relationship, it's considered to be language-independent, with parsers available for almost every language.
JSON Data Types, Syntax and Structure
JSON Data Types:
- Number
- Either as Integer: (…,-1,0,1,…) or as Real: (3,141592…)
- String
- double-quoted Unicode: "Jonh Doe"
- Boolean
- true or false
- Array
- an ordered sequence of values, comma-separated and enclosed in square brackets [ ]:
["Value1","Value2","Value2"]
- Object
- a collection of key:value pairs, comma-separated and enclosed in curly braces { }:
{"Key1":"Value1" , "Key2":"Value2" , "Key3":"Value3"}
- Null Value
- null
JSON Syntax and Structure
A typical JSON file could be presented like this:
{
"firstName": "John", //String
"lastName": "Doe",
"age": 39, //Number
"has_kids": false, //Boolean
"Hobbies":["Reading","Skating","Music"] //Array
"address": { //Object
"streetAddress": "Somewhere over the rainbow 2-1",
"city": "New York",
"postalCode": 10021
},
"phoneNumber": [ //Array and Object
{ "type": "home",
"number": 2125551234 },
{ "type": "fax",
"number": null //null value
}],
}
However, like Javascript, JSON can be formatted to be single-line.
Pratical Examples with JavaScript
Fetch and Include JSON File
I will show now, how to use JavaScript to print JSON files on a HTML page. I will use the Twitter API to get a JSON file.
http://twitter.com/statuses/public_timeline.json this link allow us to download a JSON file with the last 20 public tweets on Twitter. Due security reasons (XSS), we can not fetch the file with using XmlHttpRequest (AJAX) directly as so, we include it directly in the HTML page:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Your Website</title>
</head>
<body>
<script type="text/javascript" src="http://twitter.com/statuses/public_timeline.json?
callback=public_timeline"></script>
</body>
</html>
Print the JSON values
Notice the ?callback=public_timeline? We're using it, because if we download the file directly, we won't be able to use it sincee it's not assigned to any variable, or object or any other kind of javascript resource, so the Twitter API allow us to call the file with a callback function and so making the file usable for manipulation.
We now have the JSON file with a callback function to make it usable. We print its values by adding the following script:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Your Website</title>
</head>
<body>
<script type="text/javascript" src="http://twitter.com/statuses/public_timeline.json?
callback=public_timeline"></script>
<script type="text/javascript">
var tweet;
function public_timeline(data){
tweet = data;
for(var i in tweet){
document.write(tweet[i].user.name);
document.write(tweet[i].text);
document.write(tweet[i].created_at);
}
}
</script>
</body>
</html>
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.
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:
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"
Pratical Examples with PHP
Create and Decode a JSON Object
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:
<?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
?>
The json_encode() function actually takes care of the JSON syntax, and even makes the object "user" inside the JSON. To decode it, we just use the json_decode() and the PHP will transform the JSON into an associative array, pretty much the opposite of the json_encode().
Twitter API Introduction
"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."
in Twitter About Us page
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
in Paul Adams in The Real Social Network
An API (Application Programming Interface) it's a interface implemented by a service that allows programmers to interact with other software
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
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 YouTube or Vimeo
My choice of using the Twitter API, is due to two reasons:
- It's relatively easy, and pretty straightforward to use
- It's well documented
What you need to know
Among several things, i believe that these three are essential to use the Twitter's API:
- The API is entirely HTTP-based
- Where methods to retrieve data use the GET request.
- publishing, modifying or destroying data on Twitter requires the POST request.
- A command-line is all you need to interact with the Twitter API
- There are Twitter API libraries for almost any language
Create a Small Twitter Client
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
So the process i'm going to use is:
- #Get the JSON File with PHP and cURL
- #Print the tweets
- #Serialize a form with JavaScript
- Send the form to PHP with AJAX
- Post the tweet using a PHP Twitter Library
Get the JSON with PHP and cURL
<?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);
?>
The ability to use 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
<?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"];
}
?>
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:
Serialize a form with JavaScript
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 eval() 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
To save a few lines i'll be using the jQuery Framework
<form action="lol.php" method="get" accept-charset="utf-8">
<input type="text" name="lol" value="" id="lol">
<input type="text" name="lmao" value="" id="lmao">
<p><input type="submit" id="submit" value="Continue →"></p>
</form>
<script type="text/javascript" charset="utf-8" src="http://www.JSON.org/json2.js"></script>
<script type="text/javascript" charset="utf-8" src="http://code.jquery.com/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.input1 = $('#lol').val();
obj.input2 = $('#lmao').val()
obj2string = JSON.stringify(obj);//convert object to json string
alert(obj2string);
$.post("sendTweet.php",obj2string,function(data)){
tweet = JSON.parse(data);//convert json string to object
}
});
});
</script>