Creating an Array of up to 4 Node Outputs

Hey everybody, this problem has left me scratching my brain so wondering if anyone in the community has a better idea of how to solve this than me. I am using some AI generator APIs and it returns a JSON string of “text”: “text output goes here”.

I want to run this 4 times and then make an array of the 4 “text” outputs ideally following the structure of

[
{
“Outputs”: [
{
“Generated”: “First text output”
},
{
“Generated”: “Second text output”
}
]
}
]

with that being created regardless of if there is just 1 text generated or 2, 3 or 4. I can’t figure out how to get this done with the function node but if someone can point me in the right direction that’d be great.

I’ve tried doing this with a webhook response and then building the json manually but then the json gets broken if there is a linebreak or similar.

Hey @stuart, I hope you’re well?

So to break this down a bit, n8n nodes would typically run once for each item they receive. So the first step would be to pass on 4 dummy items to the HTTP Request node (I assume that’s the one you’re using) to make sure it calls your API 4 times. I am doing this by using the JS Array() constructor in a Function node.

After the HTTP Request node ran, I am then using another Function node to create the exact result data structure you have in mind. Here is everything combined in a single workflow:

If you are okay with a slightly different format you can also use the Item Lists node instead, for example like so:

2 Likes

Awesome, thanks for this! Let me see if I can get it working correctly. Appreciate the time spent to help on this.

1 Like