Store/Retrieve a Map in a Attribute via SendEvent

I've noticed that you can store any object in an attribute (updated via SendEvent) and it stores the value as a toString, but obviously if you store a Map object, it cannot easily be converted back to Map when currentValue is called. Any tips for this problem or is the answer that you write out the Map into many individual attributes and recover them that way? Maybe I'm missing something in how to rebuild a Map from a toString (which isn't JSON unfortunately) so not sure where to go from here....

What do you need to do with the data? It sounds like you need some storage that you can access and update. Have you considered using state?

Yeah... I'm thinking that's the better option, and also considering parsing out the Map into Json and storing that in the Attribute/SendEvent... Mmmmm options to consider

1 Like

If you really want to store it in an attribute, you could use JsonOutput() to flatten the map to a JSON string to store, then use JsonSlurper() to un-flatten when you pull it out of the attribute.

Yeah, if you need to store this in an attribute, I think that's what you'll have to do. Hubitat does have a documented JSON_OBJECT type for attributes, but when I retrieve it, all I get is a string as far as I can tell, so you'd have to re-convert it to a Map, List, or whatever data structure you're using to represent the data in Groovy. But you really only need an attribute if you need users of the device to be able to respond to events where these values change or for arbitrary apps to be able to access this data (e.g., as one might with lightEffects or supportedFanSpeeds, two JSON_OBJECT attributes I can think of).

If it's for internal use within your driver, the idea above of storing it to state should work just as well. State natively supports Maps and Lists, so you wouldn't have to do any work yourself. If the data never changes, you could also use something like a static field (@Field) to hold this data and refer to it in your own code as needed. Here's an example of that for the lightEffects attribute:

1 Like

Download the Hubitat app