Lua - json.lua
Purpose
A library to encode or decode JSON :
- json.decode : Converts a JSON string into a Lua table, to easily manipulate result of API in Domoticz.
- json.encode : Converts a Lua table into a serialised JSON string.
Source
http://regex.info/blog/lua/json
Example of use
Example from this thread : [1]
-- json = (loadfile "scripts/lua/JSON.lua")() -- using relative path
json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")() -- For Linux
json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")() -- For Windows
local wuAPIkey='123456abcdefg' -- set up here your wuAPIkey
local city='Paris' -- set up here a city
local countryCode='FR' -- set up here the 2 digit country code of the country
-- API Wunderground
local config=assert(io.popen('curl http://api.wunderground.com/api/'..wuAPIkey..'/conditions/q/'..countryCode..'/'..city..'.json'))
-- local config=assert(io.popen('curl "http://192.168.1.11:8080/json.htm?type=devices&rid=111"')) -- notice double quotes
local location = config:read('*all')
config:close()
local jsonLocation = json:decode(location)
latitude = jsonLocation.current_observation.display_location.latitude
longitude = jsonLocation.current_observation.display_location.longitude
altitude = jsonLocation.current_observation.display_location.elevation
relativePressure = jsonLocation.current_observation.pressure_mb
-- CurrentCounter = jsonValue.result[1].Counter -- value from "Counter", inside "result" bloc number 1 (even if it's the only one)
print('Lat: '..latitude..'Long: '..longitude..'Alt: '..altitude)
The library is included in the latest domoticz version
Some considerations
The script example above has the potential of locking the Domoticz's event system for up to 10 seconds in case that the assert function doesn't return within that time. That can for example happen if there is a delay on the Internet or some other reason that makes the server not responding immediately. Ten seconds of waiting is a very long time to stall the Domoticz's event system and this script and similar constructions while they may work at some point they can be devastating and should be avoided at all costs. Here is an example how you can do instead.