How to handle JSON data using the electric imp.
I’ve had more requests for examples of accessing JSON data using an electric imp. I use it to collect weather information from weather underground. Here’s some skeleton code to highlight what you need..
local astronomy = OutputPort("Astronomy","number");
function getAstronomyData() {
astronomy.set(1); //initiates outbound connection to retreive astronomy data
}function dumptable(p, t) {
foreach(key, value in t) {
if (typeof value == "table") {
dumptable(p+"."+key, value);
}
else server.log(p+"."+key + " = " + value);
}
}//this class receives the json data
class Astronomy extends InputPort {
function set(payload) {
//to figure out json structure uncomment the following and check the log output
//dumptable("",payload);
//all the data is considered a string, so convert to integer or whatever as necessary
local variable = payload.moon_phase.sunset.hour.tointeger();
doSomethingWith(variable);
//schedule another update in 1 minute
imp.wakeup(60, getAstronomyData);
}
}function boot() {
//invoke a call to get the astronomy data here
getAstronomyData(); // or use imp.wakeup() to specify a time to invoke
}imp.configure("Outdoor Automation", [Astronomy("astronomy","string") ], [astronomy]);
In the planner, setup an HTTP request which sends the request in the form of a GET request specifying the url (which, in the case of weather underground, includes the api key). Set the content type to json.
Connected an arrow from your application to the HTTP request and one from the HTTP request back to the application.
The way it works is that when you write to the HTTP request, the URL is called. When data is returned, it will invoke Astronomy.set() (defined in imp.configure(), which you need to provide) which then parses the data.
A dumptable function is provided in order to help you figure out the structure of the json data the first time to know how to extract it.
Hope this helps.