Nav links

Tuesday, 16 June 2009

BoM goes JSON

The Bureau of Meterology has quietly released JSON feeds of their weather observations. At the base of their individual observation pages, such as Broome you'll see a link to a couple of JSON formats. This comes years after they first promised an XML feed, and for many developers will prove much more useful. They are static JSON pages rather than a service responding to varying querystrings, but it's a good start.



I have changed Weather Chart from HTML screen-scraping to JSON. Although there's no visible difference to the end user, it has made the code somewhat nicer. In the sample below I have replaced a long and complicated regular expression with a straightforward array index.



Original:



    //==== Get arrays of time, temperature and rainfall

    preg_match_all('@<tr[^>]*>\s*<td>\d\d/([^<]*)</td>\s*<td>(.*?)</td>(?:[^\n]*?\n){11,12}\s*<td>(.*?)</td>@', $htmlData, $matches);

    $labels  = $matches[1];

    $temperatures = $matches[2];

    $rain = $matches[3];




New:



    $labels = $wData["observations"]["data"]["local_date_time_full"];

    $temperatures = $wData["observations"]["data"]["air_temp"];

    $rain = $wData["observations"]["data"]["rain_trace"];





An additional benefit of switching to JSON is that changes to the BoM's HTML page layout will no longer have the potential to break the Weather Chart.