Perl to JavaScript Data via JSON

I have a Perl script monitoring serial ports for sensor data, that data is then to be accessed in a web page via AJAX so needs to be readable by JavaScript. I’m using JSON as the data format to transport the data.

Writing JSON in Perl

Install the JSON module with CPAN if not already installed. Then simply construct a hash table, or a hash of hashes to create a name hierarchy. Once the hash is created, use the to_json function to format the hash as a JSON string and write that string to a text file.

my $json->{"temp"} = {"f" => ($ad1 * 100.0 / 0x3ff) * 9 / 5 + 32, "c" => ($ad1 * 100.0 / 0x3ff)};
$json->{"water"} = $dio4;

$json_text = to_json $json;

open FILE, ">xbee.json";
print FILE $json_text;
close FILE;

Reading JSON in JavaScript

Now that JSON file can be accessed from a web browser to display the results. Using jQuery there is a .getJSON function that will read the file and unpack the JSON format into a JavaScript variable. Once in the variable, as data is here, the hashes written in Perl are accessed as child objects of the variable. Eg. the hash water is simple accessed as data.water in Javascript.


$.getJSON('xbee.php', function(data) {
 $('#basement_temp').html(data.temp.f.toFixed(1));
 if (data.water != '0') {
$('#basement_water').removeClass('sensor_alert').addClass('sensor_ok');
 } else {
$('#basement_water').removeClass('sensor_ok').addClass('sensor_alert');
 }
 });