Using SWITCH node

Guys I need a help to use switch node with expression mode, someone pls could show me an example with 4 outputs?

I already use in rule mode, i would like to explore more options with expressions.

I read documentation but i didn’t think too much clear.

Hi @Fabio_Valentim,
if you are looking for example workflows using our Switch Node you can go to n8n workflow templates and use the “Integrations” filter.

Hi marcus, there is no relevant example, this template is rule based, i would like to know how to use expression based, since i put any information but nothing appears.

image

In Expression mode you have to write an expression in the “Output” parameter which resolves to the output index you want to route the item to. So it has to resolve to: 0, 1, 2 or 3

Here a basic example which routes each of the 4 items to a different output depending on its id:

I hope that is helpful!

2 Likes

Hi, do you mean that we add to a json a field that control the output ?

Very sorry, I do not understand the quesiton.

Hi all,

I’ve already spent an hour searching for how expressions work in Switch mode, and I have to admit, even if I love n8n, this is frustrating. Yes, there’s documentation for switch mode, but there are no examples for the expression part. I believe examples should automatically be part of any documentation - I mean, the node has just 2 modes!

Anyway, after searching and testing, I can share a short how-to below for anyone else.

Some generic info
When using expressions, please keep in mind you can only use one-line code!
As written above by Jan and in the documentation, the output must be a number.
If 4 outputs are needed, numbers 0, 1, 2, 3 must be used as output.

Example
I need 3 outputs based on values in attributes:

  • gitHubUpdatedAt
  • updatedAt
  • exists

I will therefore create 3 conditions, which I can present in JavaScript as follows:

if($json.gitHubUpdatedAt > $json.updatedAt && $json.exists) { 
    return 2; 
}
else if ($json.gitHubUpdatedAt > $json.updatedAt && !$json.exists) {
    return 1;
}
else {
    return 0;
}

Using one-line code, the correct expression will therefore be:

{{ ($json.gitHubUpdatedAt > $json.updatedAt && $json.exists) ? 2 : (($json.gitHubUpdatedAt > $json.updatedAt && !$json.exists) ? 1 : 0) }}

I hope it will save someone’s else time.
TAG: Expression Mode in Switch Node