Comm Lab Web Week 4

Web Services


JSON stands for JavaScript Object Notation. It has become a standard way to provide machine readable data to and from web services. Despite the fact that JavaScript is part of it's title, it is generally useful in all programming languages.

(XML - Extensible Markup Language is another popular means for providing machine readable data to and from web services.)

As stated on the site: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

A simple JSON object

	fist_name: "Shawn",
	last_name: "Van Every

An array of JSON objects

	fist_name: "Shawn",
	last_name: "Van Every"
	fist_name: "Joe",
	last_name: "Frank"
values can be string, number, null or boolean (true/false)

One JSON data feed that might be interesting is from OpenWeatherMap. Their API is documented here.

This is the feed for New York City's data: which yields the following:

{"coord":{"lon":-74.005966,"lat":40.714272},"sys":{"country":"US","sunrise":1380106043,"sunset":1380149242},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"gdps stations","main":{"temp":60.44,"pressure":1013,"temp_min":54,"temp_max":66.2,"humidity":88},"wind":{"speed":2.22,"gust":3.08,"deg":285},"rain":{"3h":0},"clouds":{"all":0},"dt":1380076310,"id":5128581,"name":"New York","cod":200}

We can make this JSON easier to read by doing some formatting:

After formatting we get the following:

         "description":"Sky is Clear",
   "base":"gdps stations",
   "name":"New York",

We see a lot of what we might expect, temp, pressure, humidity and so on. Also of interest is the sunrise and sunset time. These are particularly interesting because they are represented in standard "unix timestamp" which is the number of seconds from January 1, 1970. - Command line: date "+%s"

Requesting and Parsing JSON with PHP

First need to request the JSON from the server. To do this, there is a nice tool called curl which is usable within PHP.

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, ""); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$return_data = curl_exec($curl); 


Once we have the raw JSON, we'll need to use PHP's JSON functions to decode it into something usable in PHP:

$return_object = json_decode($return_data);
print_r prints out the variable in human readable form, offering insight into the structure. It is a nice way to figure out how to get access to the data you need. In this example, you see that we have an overall object and several objects as properties of that object. For instance, "temp" is a property of "main" which is a property of the original object. You can get at the temp property by using the following syntax:
print("The temp is: " . $return_object->main->temp);

So.. What could you do with this data?