Lua - json.lua

From Domoticz
Jump to: navigation, search


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.


Example of use

Example from this thread : [1]

       json = (loadfile "/home/pi/domoticz/scripts/lua/JSON.lua")()  -- For Linux
       json = (loadfile "D:\\Domoticz\\scripts\\lua\\json.lua")()  -- For Windows
       local wuAPIkey='xxx'    -- 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'..wuAPIkey..'/conditions/q/'..countryCode..'/''.json'))
       -- local config=assert(io.popen('curl ""')) -- notice double quotes
       local location = config:read('*all')
       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