I have a case where I want to set a variable to be an object using a template, but instead I am getting a string that contains the object as a JSON string. I have the same problem if I want to set a variable to an array. I just get a JSON string of the array.
My intent is to reduce verbosity (and repetitiveness) of logic in other templates. Does anyone have any ideas?
Object example:
variables:
data: "{{trigger.event.data}}"
#this next line fails because data is a JSON string rather than the desired object
value: "{{data.value if data.value is string else data.value|random if data.value}}"
Array example:
variables:
message: "{{trigger.event.data.message}}"
#message is always a string even if trigger.event.data.message was an array
value: "{{message if message is string else message|random if message}}"
As far as I understand, a Jinja template always outputs a single string. So you’d need to make a variable for each field in the data block for this to work.
@Burningstone, that’s what I ended up doing. I wonder if the parser for the new variables feature could be enhanced to recognize JSON and deserialize it automatically?
@lonebaggie, that’s an interesting technique. I can’t use it in this case because the values cannot be global, but I will keep it in mind if I run into a scenario where it will help.