Page 1 of 1

Match in json.

Posted: Sunday 16 February 2020 1:19
by OedzesG
hallo me again.. :D

is there someone how know how to find a match in a json en get some value return if true?

its for holidays..

this is json output....

Spoiler: show

Code: Select all

{
  "year": "2020",
  "country_iso_alpha_2": "NL",
  "holidays": [
    {
      "date_id": 97519,
      "date": "1-1-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "1",
      "month": "1",
      "month_name": "January",
      "month_name_local": "januari",
      "year_day": "1",
      "month_day": "1",
      "week_day": "3",
      "day_name": "Wednesday",
      "day_name_local": "woensdag",
      "iso_date": "01/01/2020 00:00:00",
      "iso_week": "1",
      "is_weekend": false,
      "every_year_on_same_date": true,
      "global": true,
      "name": "New Year's Day",
      "name_local": "Nieuwjaarsdag",
      "type": "Public",
      "formated_date": "01-01-2020 00:00 AM"
    },
    {
      "date_id": 97619,
      "date": "10-4-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "4",
      "month_name": "April",
      "month_name_local": "april",
      "year_day": "101",
      "month_day": "10",
      "week_day": "5",
      "day_name": "Friday",
      "day_name_local": "vrijdag",
      "iso_date": "04/10/2020 00:00:00",
      "iso_week": "15",
      "is_weekend": false,
      "every_year_on_same_date": false,
      "global": true,
      "name": "Good Friday",
      "name_local": "Goede Vrijdag",
      "type": "School, Authorities",
      "formated_date": "10-04-2020 00:00 AM"
    },
    {
      "date_id": 97621,
      "date": "12-4-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "4",
      "month_name": "April",
      "month_name_local": "april",
      "year_day": "103",
      "month_day": "12",
      "week_day": "7",
      "day_name": "Sunday",
      "day_name_local": "zondag",
      "iso_date": "04/12/2020 00:00:00",
      "iso_week": "15",
      "is_weekend": true,
      "every_year_on_same_date": false,
      "global": true,
      "name": "Easter Sunday",
      "name_local": "Paasfeest",
      "type": "Public",
      "formated_date": "12-04-2020 00:00 AM"
    },
    {
      "date_id": 97622,
      "date": "13-4-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "4",
      "month_name": "April",
      "month_name_local": "april",
      "year_day": "104",
      "month_day": "13",
      "week_day": "1",
      "day_name": "Monday",
      "day_name_local": "maandag",
      "iso_date": "04/13/2020 00:00:00",
      "iso_week": "16",
      "is_weekend": false,
      "every_year_on_same_date": false,
      "global": true,
      "name": "Easter Monday",
      "name_local": " Pasen",
      "type": "Public",
      "formated_date": "13-04-2020 00:00 AM"
    },
    {
      "date_id": 97636,
      "date": "27-4-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "4",
      "month_name": "April",
      "month_name_local": "april",
      "year_day": "118",
      "month_day": "27",
      "week_day": "1",
      "day_name": "Monday",
      "day_name_local": "maandag",
      "iso_date": "04/27/2020 00:00:00",
      "iso_week": "18",
      "is_weekend": false,
      "every_year_on_same_date": true,
      "global": true,
      "name": "King's Day",
      "name_local": "Koningsdag",
      "type": "Public",
      "formated_date": "27-04-2020 00:00 AM"
    },
    {
      "date_id": 97644,
      "date": "5-5-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "5",
      "month_name": "May",
      "month_name_local": "mei",
      "year_day": "126",
      "month_day": "5",
      "week_day": "2",
      "day_name": "Tuesday",
      "day_name_local": "dinsdag",
      "iso_date": "05/05/2020 00:00:00",
      "iso_week": "19",
      "is_weekend": false,
      "every_year_on_same_date": true,
      "global": true,
      "name": "Liberation Day",
      "name_local": "Bevrijdingsdag",
      "type": "School, Authorities",
      "formated_date": "05-05-2020 00:00 AM"
    },
    {
      "date_id": 97660,
      "date": "21-5-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "5",
      "month_name": "May",
      "month_name_local": "mei",
      "year_day": "142",
      "month_day": "21",
      "week_day": "4",
      "day_name": "Thursday",
      "day_name_local": "donderdag",
      "iso_date": "05/21/2020 00:00:00",
      "iso_week": "21",
      "is_weekend": false,
      "every_year_on_same_date": false,
      "global": true,
      "name": "Ascension Day",
      "name_local": "Hemelvaartsdag",
      "type": "Public",
      "formated_date": "21-05-2020 00:00 AM"
    },
    {
      "date_id": 97670,
      "date": "31-5-2020 00:00:00",
      "culture_info": "nl-NL",
      "year": "2020",
      "quarter": "2",
      "month": "5",
      "month_name": "May",
      "month_name_local": "mei",
      "year_day": "152",
      "month_day": "31",
      "week_day": "7",
      "day_name": "Sunday",
      "day_name_local": "zondag",
      "iso_date": "05/31/2020 00:00:00",
      "iso_week": "22",
      "is_weekend": true,
      "every_year_on_same_date": false,
      "global": true,
      "name": "Whit Sunday",
      "name_local": "1e pinksterdag",
      "type": "Public",
      "formated_date": "31-05-2020 00:00 AM"[code][/spoiler]

Re: Match in json.

Posted: Sunday 16 February 2020 7:48
by waaren
OedzesG wrote: Sunday 16 February 2020 1:19 is there someone how know how to find a match in a json en get some value return if true?
Please don't let us guess what you mean. Best to provide some pseudo code to explain what you try to achieve.

something like below ?

Code: Select all

local today = os.date('%m/%d/%Y')
for _, record in ipairs(json.holidays) do
    if record.iso_date:match(today) then
        print('Today is ' .. record.name_local)
    end 
end 

Re: Match in json.

Posted: Sunday 16 February 2020 20:47
by OedzesG
something like below ?
thnx waaren...

exactly what i need.. !

is it true that "else" is not working after a match?

this is the script so far...

Code: Select all


		
	--<[================================================================================================]>--	
	--<[ 				Feestdagen api door Reinders.eu  				    ]>--
	--<[================================================================================================]>--
	
		local scriptVersion = ' testing '
		local scriptVar = ' feestdagen ' .. scriptVersion
	
	--<[=============================]>-- Your settings below this line --<[============================]>--		
				
		local country 		= 'NL'		
		local apiKey 		= 'xxx'
		
	--<[==========================]>-- No changes required below this line --<[==========================]>--		
		
	return 	{
				on =
			{
				timer = 
			{ 
				'every minute',
			},
				httpResponses 	= { scriptVar,
			}, 
			},
				logging 		= { level 	= domoticz.LOG_DEBUG,
									marker 	= scriptVar,
			},
				data 			= { eventName 	= { initial = {} 
			},
			},
		
	execute = function(dz, item)

	
	if (item.isTimer) then
				
		local url = 'https://address.whacky.nl/api/date/holiday?api_key=' .. apiKey .. 
						    '&iso_alpha_2_country=' .. country .. '&year=' .. dz.time.year 
			
		dz.openURL({ url = url, callback = scriptVar }) end 

		if (item.isHTTPResponse) then
		if (item.ok) then
		local jsonholidays = item.json.holidays
		
			local testTime = '01/01/2020 00:00:00'
			local today = os.date('%m/%d/%Y')
                
			for _, record in ipairs(jsonholidays) do
			if record.iso_date:match(testTime) then
			dz.data.eventName = record.name_local else -- else is here not working?? 
			dz.date.eventName = 'geen feestdag'
					
				end 
			end  	
						
			dz.log( ' feestdag is ' .. (dz.data.eventName)) 
					
				end 
			end 
		
		end 
	} 		
	
when i remove

Code: Select all

 else -- else is here not working?? 
			dz.date.eventName = 'geen feestdag'
the data in de log is correct, but in this way its always "geen feestdag actief"

Re: Match in json.

Posted: Sunday 16 February 2020 22:55
by waaren
OedzesG wrote: Sunday 16 February 2020 20:47
something like below ?
is it true that "else" is not working after a match?
No. but your logic is wrong. You can see what happens if you add some loglines in the for loop both in the if and in the else part.
Below script should produce the expected result.

Code: Select all

        
    --<[================================================================================================]>--    
    --<[                 Feestdagen api door Reinders.eu                      ]>--
    --<[================================================================================================]>--
    
        local scriptVersion = ' testing '
        local scriptVar = ' feestdagen ' .. scriptVersion
    
    --<[=============================]>-- Your settings below this line --<[============================]>--        
                
        local country         = 'NL'        
        local apiKey         = 'xxx'
        
    --<[==========================]>-- No changes required below this line --<[==========================]>--        
        
return     
{
    on =
    {
        timer = 
        { 
            'every minute',
        },
        httpResponses = 
        { 
            scriptVar,
        }, 
    },

    logging = 
    { 
        level = domoticz.LOG_DEBUG,
        marker     = scriptVar,
    },
    
    data = 
    { 
        eventName = 
        {
            initial = {},
        },
    },

    execute = function(dz, item)

        if item.isTimer then
            local url = 'https://address.whacky.nl/api/date/holiday?api_key=' .. apiKey .. 
                                '&iso_alpha_2_country=' .. country .. '&year=' .. dz.time.year 
            dz.openURL({ url = url, callback = scriptVar }) 
            return
        end 

        if item.ok then
            local jsonholidays = item.json.holidays
            
            local testTime = '01/01/2020'
            local now = os.date('%m/%d/%Y') 
            
            dz.date.eventName = 'geen feestdag' -- initialise with 'geen feestdag'
            
            for _, record in ipairs(jsonholidays) do
                if record.iso_date:match(testTime) then
                    dz.data.eventName = record.name_local 
                end 
            end
                
            dz.log( ' feestdag is ' .. (dz.data.eventName)) 
        end 
    end 
}

Re: Match in json.

Posted: Monday 17 February 2020 0:04
by OedzesG
No. but your logic is wrong

thanks Waaren!

this way you learn something every day! : D

the finanal thing is getting te data to another script...

so i ad an helper (read on wiki)

Code: Select all


       
    --<[================================================================================================]>--    
    --<[        		        	 Feestdagen api door Reinders.eu          	        ]>--
    --<[================================================================================================]>--
    
        local scriptVersion = ' testing '
        local scriptVar = ' feestdagen ' .. scriptVersion
    
    --<[=============================]>-- Your settings below this line --<[============================]>--        
                
        local country         = 'NL'        
        local apiKey          = '8FE0EFD9-4B5C-48F6-81C2-4D0A9D062C14'
      
        
    --<[==========================]>-- No changes required below this line --<[==========================]>--        
        
    return     
		    {
		    	on =
		    {
			    timer = 
            { 
                'every minute',
            },
			    httpResponses 	= { scriptVar,
            }, 
		    },
			    logging 		= { level 	= domoticz.LOG_DEBUG,
						    		marker    = scriptVar,
		    },
		    	helpers 		= {},
			    data 			= { eventName = { initial = {}
            },
		    },

    execute = function(dz, item)

        if item.isTimer then
            local url = 'https://address.whacky.nl/api/date/holiday?api_key=' .. apiKey .. 
                        '&iso_alpha_2_country=' .. country .. '&year=' .. dz.time.year 
            dz.openURL({ url = url, callback = scriptVar }) 
            return
        end 

        if item.ok then
            local jsonholidays = item.json.holidays							
            
            local testTime = '01/01/2020'
            local today = os.date('%m/%d/%Y') 
            
            dz.data.eventName = 'geen feestdag' 
            dz.devices(scriptSwitch).switchOff().silent()
            
            for _, record in ipairs(jsonholidays) do
                if record.iso_date:match(today) then
                    dz.devices(scriptSwitch).switchOn().silent()
                    dz.data.eventName = record.name_local 
                end 
            end
                
            dz.log( ' feestdag is ' .. (dz.data.eventName)) 
        end 
    end 
}


and for test i made a verry simple script to check the data is there, but it giving my: nil

Code: Select all

return {
	on = {
	
		timer = {' every minute'},
		
		},
	
	execute = function(dz, item)
	    
	  dz.log(dz.globalData.eventName) 

	end
}

Re: Match in json.

Posted: Monday 17 February 2020 0:18
by waaren
OedzesG wrote: Monday 17 February 2020 0:04 [the final thing is getting te data to another script...
so i ad an helper (read on wiki)
If you read all the lines on the helper stuff on the wiki you will see that a helper function is something that should be defined in global_data. The wiki and this forum both show quite a number of examples on how to do that.

Re: Match in json.

Posted: Monday 17 February 2020 9:39
by OedzesG
helper function is something that should be defined in global_data.
created an global_data.lua file:

Code: Select all


	return {
        helpers     =   {},
       
       
        data        =   {
                        	eventName = { initial = {}, },
       
                        }
    }

25 times checked the syntaxes, but unfortunately i do net get the right data..

in the log it chaged from "nil" to :

Code: Select all

2020-02-17 09:36:00.426 Status: dzVents: Info: ------ Start external script: test1.lua:, trigger: " every minute"
2020-02-17 09:36:00.426 Status: dzVents: Info: {}
2020-02-17 09:36:00.427 Status: dzVents: Info: ------ Finished test1.lua

Re: Match in json.

Posted: Monday 17 February 2020 11:48
by waaren
OedzesG wrote: Monday 17 February 2020 9:39 25 times checked the syntaxes, but unfortunately i do net get the right data..
Have a look at 3 parts below

Code: Select all

--[[ global_data.lua 
 
    this global_data.lua allows the persistent storage of a table with the public holidays of a country and offers
    a helpers function to check if a given date (in the format yyyy-mm-dd) is stored in the table
    
 
 ]]-- 
return 
{
    data = 
    {
        holidays = 
        { 
            initial = {}, 
        },
    },

    helpers =   
    {
      -- this function returns the name of the found holiday for the given date or false if no holiday was found
      isHoliday = function(dz, rawDate)
        for holiday, hDate in pairs(dz.globalData.holidays) do
            if hDate == rawDate then
                return holiday
            end
        end
        return false
      end
    },
}

Code: Select all

--[[ getHolidays.lua

    this scripts can be used to initialise or refresh the global_data holiday table

]]

local scriptVersion = ' testing '
local scriptVar = ' feestdagen ' .. scriptVersion

return     
{
    on =
    {
        timer = 
        { 
            'at 12:15', -- Only needed once a year or every time global_data holiday table needs to be refreshed
        },

        httpResponses     = 
        { 
            scriptVar,
        }, 
    },

    logging = 
    { 
        level = domoticz.LOG_DEBUG, -- set to Error when script is tested and OK
        marker = scriptVar,
    },

    execute = function(dz, item)

        if item.isTimer then
            local country         = 'NL'        
            local apiKey          = '8FE0EFD9-4B5C-48F6-81C2-4D0A9D062C14'

            local url = 'https://address.whacky.nl/api/date/holiday?api_key=' .. apiKey .. 
                        '&iso_alpha_2_country=' .. country .. '&year=' .. dz.time.year 
            dz.openURL({ url = url, callback = scriptVar }) 
            return
        end 

        if item.ok then

           local function isoTorawDateformat(iso)
                -- iso-date format: mm/dd/yyyy hh:mm:ss
                -- rawDate format: yyyy-mm-dd
               return iso:sub(7,10) .. '-' .. iso:sub(1,2) .. '-' .. iso:sub(4,5)
            end

            for _, record in ipairs(item.json.holidays) do
                dz.globalData.holidays[record.name_local] = isoTorawDateformat(record.iso_date)
            end

            dz.utils.dumpTable(dz.globalData) -- Only in use during development
        end 
    end 
}

Code: Select all

--[[    testHolidays.lua

    example script to show how to get information from global_data using a helper functions

    Please note that you will have to pass the domoticz object (here dz) if the helper function needs information from that object !!
    
]]--
return     
{
    on =
    {
        timer = 
        { 
            'every minute', 
        },
    },

    execute = function(dz)

        testDate = '2020-12-25' -- Christmas
        
        dz.log(testDate .. ' is ' .. '"' ..(dz.helpers.isHoliday( dz, testDate) or 'no holiday') ..'"',dz.LOG_FORCE )
        dz.log(dz.time.rawDate .. ' is ' .. '"' .. (dz.helpers.isHoliday( dz, dz.time.rawDate) or 'no holiday') .. '"',dz.LOG_FORCE )
    end 
}

Re: Match in json.

Posted: Monday 17 February 2020 13:40
by OedzesG
Have a look at 3 parts below
thnx waaren!

works great!

but the problem is....

i almoast dont understand a wordt of what written over there, just starten to test with normal data.. and in the future i want store maybee some more data witch i simply can call in anotherscript with: dz.globalData." dataname "

for dzVents and now this script works great!


but for me to understand, this script is 500 steps too far ahead.

Re: Match in json.

Posted: Monday 17 February 2020 13:50
by waaren
OedzesG wrote: Monday 17 February 2020 13:40 [but for me to understand, this script is 500 steps too far ahead.
Just ask the lines you don't understand after searching on the forum and wiki and I will try to explain step by step.

Re: Match in json.

Posted: Monday 17 February 2020 14:01
by OedzesG
Just ask the lines you don't understand after searching on the forum and wiki and I will try to explain step by step.
Thnx waaren!!

Re: Match in json.

Posted: Monday 17 February 2020 16:22
by OedzesG
Prerfecly working for me like this...

there were some parts i do understand :D

now data is everywere avalible with. dz.globalData.eventName.

big thanks!

Code: Select all


	
	--<[================================================================================================]>--	
	--<[ 					dzVents Feestdagen  		  		  	    ]>--
	--<[================================================================================================]>--
	
		
		local scriptVersion = ' v 1.0 '
		local scriptVar = ' feestdagen ' .. scriptVersion


	--<[=============================]>-- Your settings below this line --<[============================]>--		
				
		
		local country 	= 'NL'		
		local apiKey 	= 'xx'
		
	
	--<[==========================]>-- No changes required below this line --<[==========================]>--		
		
	

	return 	{
				on =
			{
				timer 		= { 'at 00:00',
			},
				httpResponses 	= { scriptVar,
			}, 
			},
				logging 	= { level 	= domoticz.LOG_ERROR,
						    marker 	= scriptVar,
			},
	
			
    execute = function(dz, item)

        if item.isTimer then
       
            local url = 'https://address.whacky.nl/api/date/holiday?api_key=' .. apiKey .. 
                        '&iso_alpha_2_country=' .. country .. '&year=' .. dz.time.year 
           
					dz.openURL({ url = url, callback = scriptVar }) 
				return
			end 
			
			local function logWrite(str, level)
				dz.log(tostring(str),level or dz.LOG_FORCE) 
			end 
			
				dz.globalData.initialize('eventName') 
				dz.globalData.initialize('eventActive') 

			if item.ok then
			
				local today = os.date('%m/%d/%Y')

                		for _, record in ipairs(item.json.holidays) do
					if record.iso_date:match(today) then
					dz.globalData.eventName = (record.name_local)
					dz.globalData.eventActive = 1
					logWrite( ' vandaag is een feestdag, vandaag is ' .. record.name_local ) 
					
				    	end 
				end
			end 
		end 
}