Lua - json.lua

From Domoticz
Jump to: navigation, search

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.
  • jsone.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 "/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 http://api.wunderground.com/api/'..wuAPIkey..'/conditions/q/'..countryCode..'/'..city..'.json'))
       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
       print('Lat: '..latitude..'Long: '..longitude..'Alt: '..altitude)

The library is included in the latest domoticz version