How can I pass an array to a service call via NodeRed

TL;DR: I want to construct an array using JS and then pass that array to the input_select.set_options service-call data.

I’m trying to use the input_select.set_options service, which requires an array value for the options data. I can get it work fine if I use the dev tools and manually write an array like ["option 1", "option 2", "option 3"], but in NodeRed, if I try to pass an actual array object to the service call JSON, it injects all values into one input_select option.

Here is an example setup in NR:

But here is what the entity itself is actually set to:

I’ve also tried calling the service in NR with the following JSON (no variables) but the same thing happens.

{
    "options": "['option 1', 'option 2']"
}

So is there a way to actually pass an array via the service call JSON? Or is this just an unavoidable formatting quirk?

TL:DR;

I’ve never used the input_select but tried to replicate your issue and mine worked perfectly fine.

What are you trying to do with {}"options:" "{{options}}" ?
If you wrap the {{}} in quotes you’re immediately turning that into a string; and not an array.

Proof it worked:

image

Gotcha thank you; so my issue with hard-coding it was just JSON formatting. I was able to get that to work, templating each option like this:

{
    "options": [
        "{{options.0}}",
        "{{options.1}}",
        "{{options.2}}"
    ]
}

But I’m still not satisfied here, because my goal is to pass the array directly to the service call. Is there a way to format it that would work? My issue is that the array length varies, so I would need to have a service-call node for every possible array length…

I don’t know what node you are using, but node-red-contrib-home-assistant-websocket accepts a mustache template for the data field.

Yep; the issue is that even if you pass an array to the data field via mustache template, it loads that array into a single option of the input_select. The 3rd screenshot in the original post demonstrates this.

Okay, I’ve figured out a way to get this to work, using JSONata expressions.

Instead of passing regular JSON to the service data, change it to a JSONata expression like this:
image

And then just write up any expression that won’t overly alter the data. I did $sort() in this case because my data was alphabetized anyway. It’s not the cleanest, but it works. If sorting the array is an issue, $distinct(array) will also work (while removing any duplicate entries).

2 Likes

Thank you PapaMarsh!
You got me back up and running again, and I’ve just learned a little bit more.

Much appreciated.

1 Like

Awesome! Glad it helped!