Hi, I try to use simple Pubnub Subscribe and extract json from it:
`pubnub.subscribe([ledStateChannel], function(err, result, tt) {
if(result != null && ledStateChannel in result) {
try {
local data = http.jsondecode(result[ledStateChannel]);
if ("light" in data) {
device.send("led", data["led"].tointeger());
}
} catch(ex) {
server.log("Error - " + ex);
}
}
});`
but the ‘result’ never contain json string (I did check on pubnub debug console having correct message), rather than the ‘result’ contains something like a reference to a table when I do server.log on it:
`2016-03-11 11:45:39 UTC+0 [Agent] (table : 0x7f604cce39d0)
2016-03-11 11:45:39 UTC+0 [Agent] Error - Invalid JSON (line 22)`
Any idea?
why not just print it to see what it is?
server.log("type="+typeof(result[ledStateChannel]+" result="+result[ledStateChannel])
Ah I did print the result[ledStateChannel]
and the content is (table : 0x7f604cce39d0)
and the type is ‘table’
type=table result=(table : 0x7f33b86e0270)
Or should I ask PubNub?
Reading the pubnub class documentation…
// Subscribe to one or more channels // Input: // channelsArray - array of channels to subscribe to // callback - onData callback with three parameters: // err - A string containing the error, or null on success // result - A table containing (channel, value) pairs for each message // timetoken - nanoseconds since UNIX epoch, (from PubNub service) // [timetoken] - callback with any new value since (timetoken). // // NOTE1: The callback will be initially called once with result = {} and tt = 0 after first subscribing // NOTE2: Subscribe should generally be called with the timetoken parameter ommited
result is a table. ie it has already been json decoded for you.
Thanks! it works. The table can be directly accessed:
`if ("led" in (result[ledStateChannel])) {
device.send("led", result[ledStateChannel]["led"].tointeger());
server.log("Send - " + result[ledStateChannel]["led"]);
}`
Then the result:
`2016-03-15 06:25:10 UTC+0 [Agent] type=table result=(table : 0x7f336dcd08d0)
2016-03-15 06:25:10 UTC+0 [Agent] Send - 1
2016-03-15 06:25:12 UTC+0 [Agent] type=table result=(table : 0x7f33c88fd250)
2016-03-15 06:25:12 UTC+0 [Agent] Send - 0`