Working with Jason Dictionary

I am using a Jason Dictionary to store times (the key) that rain gauge trips occur in my home automation system. If I wanted to come up with a routine that would tell me how many trips have occurred in the last 24 or 48 hours, what might that look like? I’m a bit out of practice on coding, so any help would be welcome.

For each trip:

Dictionary_Rain_Gauge.Value( = “Rain Gauge Trip Time” //Set trip time to current time
Save_Json_Dictionary(“Dictionary Rain Gauge Json”,Dictionary_Rain_Gauge)

Hi Clifford, is your JSON data object stored in the APP as a simple (and perishable) variable? So if the app quits does the data just disappear? I realize that has little to do with directly answering your question - I just wanted to see if you’re moving it somewhere more persistent that could offer different querying options.

Yes, it is William:
Save_Json_Dictionary(“Dictionary Rain Gauge Json”,Dictionary_Rain_Gauge)
Stores the jason file on my hard drive and reloads on startup. It is persistent.

You can iterate through the dictionary & count the key’s after your Start time. Something like this should work.

Public Function RainTripCount(StartDateTime As DateTime) As Integer
  Var Result As Integer
  For Each Item As DictionaryEntry In Dictionary_Rain_Gauge
    If Item.Key > StartDateTime.SQLDateTime Then
      Result = Result + 1
    End If
  Next Item
  Return Result
End Function

Untested :slightly_smiling_face:

It sounds like a SQLite database would be a better fit here. Getting a count within a date range would be trivial.

1 Like

Hi Wayne, I thought you might chime in since you’re a Jason guru of a sort and introduced me to them. Your code makes sense. Are you setting:
to a time 24 hours or 48 hours ago? Any advice on setting that time?

StateDateTime will either be DateTime.Now.SubtractInterval(0, 0, 1) or DateTime.Now.SubtractInterval(0, 0, 2) for 24 or 48 hours.

Perfect Wayne. I was just looking, and SubtractInterval is the solution. I was thinking of hours but you’re right, make it a day or two. I’ll do some testing. Thanks.

After giving this some thought, would DateTime.Now.SubtractInterval(0, 0, 1) actually yield 24 hours worth of rain trips or just from midnight to the current time? Would DateTime.Now.SubtractInterval(0, 0, 0, 24) be better suited for any 24hr stretch? For example 9PM to 9PM the next day. Hmm…

Subtracting a day should leave the time component of the object unchanged, however 12, 24, 48 hours is probably more readable give the circumstances.

Up and running. The SubtractInterval(0, 0, 2) actually simplified some code I was using. Setting up the code in a function was also a better idea, since I use rain totals for other operations. The Home Automation System now can override my irrigation watering system. Life is good! Thanks for being there, Wayne.

1 Like
Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.