Page 1 of 1

Extract value from json response

Posted: Saturday 26 March 2022 10:49
by Supertramp4
Hi, I am a newbie to domoticz, and have been experimenting with lua/dzvents scripting, and need a little help
My script calls dz.openurl with a callback

Code: Select all

/json.htm?type=devices&rid=2, which successfully returns values, 
ie 
"Data" : "309 Watt",
"LastUpdate" : "2022-03-25 19:05:43",
My question is after the

Code: Select all

if item.isHTTPResponse and item.isJSON then
  local results=item.json.result
  for i, node in pairs(results) do
    [b]local power = node.Data -- just holding the numeric part without units[/b]
    local lastUpdate = Time(node.LastUpdate)
  ...
  end
end
how do I extract the numeric value from the "node.Data" field so that power will contain a value of 309, and does not have the units of "watt" so that I can use this to update another custom sensor
Many Thanks

Re: Extract value from json response

Posted: Saturday 26 March 2022 12:39
by mgugu
You have to split the string with space separator. Unfortunately there is no built in split function un LUA. You have to make it yourself.
Check at https://www.tutorialspoint.com/how-to-s ... rogramming

Re: Extract value from json response

Posted: Saturday 26 March 2022 16:06
by Doler
Here you go

Code: Select all

		
-- Split a string separated by delimiter and return result in array
stringSplit = function(s, delimiter)   
	local result = {}
	for strmatch in (s..delimiter):gmatch('(.-)'..delimiter) do
		table.insert(result, strmatch)
	end
	return result
end

Re: Extract value from json response

Posted: Saturday 26 March 2022 20:27
by waltervl
It is fine that you experiment with JSON and OpenURL but normally this is not necessary with dzvents.
For example the lastupdate time can be read with statement
lastupdateTime = domoticz.devices(2).lastUpdate
or
lastupdateTime = device.lastUpdate
when the device 2 is the triggered device

Re: Extract value from json response

Posted: Wednesday 30 March 2022 21:58
by waltervl
I made an example script for getting the trend value out of the domoticz json respond.
Most important line:

Code: Select all

local DevTrend = item.json.result[1].trend 
no need for splitting etc.

viewtopic.php?p=288478#p288478

Re: Extract value from json response

Posted: Wednesday 30 March 2022 22:35
by Supertramp4
Hi all, thanks for your input.
@doler, the code worked, but after @waltervl input, I played a bit more, and discovered that was the way to go, and now have something working.