Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 35

Returning Item Arrays from the Code Node

Recommended resources

Introduction

Welcome back. In our previous lesson, we explored the different iteration strategies in the Code node, distinguishing between the Run Once for All Items and Run Once for Each Item modes. You learned how to access incoming data in both scenarios, which is the first step in performing any custom logic.

This lesson focuses on the crucial second step: returning your processed data from the Code node. n8n expects data in a very specific format. Mastering this output structure is essential for ensuring your custom Python logic integrates seamlessly with the rest of your workflow. We'll cover how to add, remove, and even multiply items as they pass through your code, giving you full control over the data flow.

Before we dive in, a quick note on Python environments in n8n. As n8n has evolved, so has its Python integration. The latest "Native" Python runner, which we will use, has a slightly different syntax for accessing input data than older versions. Instead of _input.all(), you will use a variable called _items in "All Items" mode. For "Each Item" mode, _input.item is now simply _item. We will use this updated syntax from now on.


The n8n Data Structure: A Strict Contract

Every node in n8n that passes data to the next one does so by producing a list of items. The Code node is no exception. When your Python script finishes, its return value must conform to this structure.

Let's look at a high-level visualization of this structure.

This diagram illustrates the core n8n data structure. The entire output is a list called 'items'. Each element in this list is an 'item' object, which must contain a key named 'json'. The value of 'json' is where your actual data resides, which can be an object or another list.

The key takeaway is that your Python code must always return a list of objects, where each object has a json key.

This is a strict contract. If your code returns anything else—a simple dictionary, a list of strings, or a list of dictionaries without the json wrapper—the workflow will fail at that node. Your proficiency with Python's data types like lists and dictionaries will make this easy to handle, but you must always remember this specific nesting requirement.


Crafting Your Return Value

How you structure your return statement depends on what you want to achieve and which execution mode you're using. The "n8n Skills" guide has an excellent section detailing the required format.

Python Code Nodes - n8n Skills - Mintlify

This guide provides many practical patterns for using Python in n8n. We will focus on the sections that define the output data contract.

Please read the following three sections: In the main content, find the section titled Return Format Requirements. This is the most critical part, showing correct and incorrect examples. Next, review the examples under Incorrect return format in the "Top 5 Error Patterns" section. This reinforces the common mistakes. Finally, look at point #4 under Best Practices, which summarizes how to return data consistently.

Let's put this into practice with a few core patterns.

Pattern 1: Modifying Items (1-to-1 Mapping)

This is the most common use case: you receive a list of items, modify each one, and return a list of the same length.

In Run Once for All Items mode, you can achieve this by building a new list. This is often the cleanest approach.




# Mode: Run Once for All Items
# Input: A list of items, each with a 'commit_hash'

processed_items = []



# _items contains the list of all input items
for item in _items:
    data = item['json']
    new_data = {
        'commit': data.get('commit_hash'),
        'short_hash': data.get('commit_hash', '')[:7], # Create a short hash
        'processed_by_python': True
    }



    # Append a new item dictionary with the required 'json' key
    processed_items.append({'json': new_data})




# Return the newly constructed list of items
return processed_items

Alternatively, because Python objects are mutable, you could modify the items in the _items list directly and then return _items. While this can work, creating a new list as shown above prevents unintended side effects and is generally easier to debug.

In Run Once for Each Item mode, the logic is simpler as n8n handles the loop. You only need to return the single, transformed item structure.




# Mode: Run Once for Each Item
# _item contains the current item being processed

data = _item['json']
new_data = {
    'commit': data.get('commit_hash'),
    'short_hash': data.get('commit_hash', '')[:7],
    'processed_by_python': True
}




# Return a single item object; n8n will collect them into a final list
return {'json': new_data}

Pattern 2: Filtering Items (N-to-M Mapping, where M < N)

Sometimes you need to remove items from the flow. To do this, you simply omit them from the list you return. Returning an empty list [] is perfectly valid and will stop that branch of the workflow.

A list comprehension is a concise and efficient way to achieve this, which should feel natural given your Python background. Let's filter a list of commits to only pass on those related to a specific feature branch.




# Mode: Run Once for All Items
# Input: Items with a 'branch' field

feature_branch = 'feature/new-auth'




# A list comprehension elegantly filters and transforms in one go
filtered_items = [
    {
        'json': {
            'commit': item['json'].get('commit'),
            'author': item['json'].get('author'),
            'message': item['json'].get('message').strip()
        }
    }
    for item in _items if item['json'].get('branch') == feature_branch
]




# This will return a list of items for the feature branch, or an empty list if none match
return filtered_items

Pattern 3: Splitting an Item (N-to-M Mapping, where M > N)

A powerful capability is to generate multiple output items from a single input item. This is useful for "un-nesting" data. For example, a single commit event might contain a list of all changed files. You can create a separate n8n item for each file to process them individually later in your workflow.

Let's see how to implement this. In Run Once for Each Item mode, you can return a list of item objects. n8n is smart enough to take all the lists returned from each execution and flatten them into one final output list.

Input: A single item: {'json': {'commit_id': 'a1b2c3d', 'changed_files': ['src/app.py', 'tests/test_app.py']}}

Code:




# Mode: Run Once for Each Item

commit_data = _item['json']
commit_id = commit_data.get('commit_id')
files = commit_data.get('changed_files', [])

new_items = []
for file_path in files:
    new_data = {
        'commit_id': commit_id,
        'file_path': file_path
    }
    new_items.append({'json': new_data})




# Return a list of items from a single execution
return new_items

Output: A list of two items:

[
  { "json": { "commit_id": "a1b2c3d", "file_path": "src/app.py" } },
  { "json": { "commit_id": "a1b2c3d", "file_path": "tests/test_app.py" } }
]

If your Code node received two such commit items, and each resulted in two file items, the final output of the node would be a single list containing all four file items.


Practical Exercise: Processing Test Results

Let's apply these concepts to a CI/CD task. A build process has finished and sends a single webhook payload to your n8n workflow with all the test results. Your job is to process this payload, filter out only the failed tests, and create a separate item for each failure so you can, for example, create a JIRA ticket for each one later.

  1. Start a new workflow. Use a Set node configured to "Set Manually" to simulate the incoming data. Paste the following JSON:

    {
      "build_id": "run-847",
      "timestamp": "2023-10-27T10:30:00Z",
      "results": [
        { "test_name": "auth::test_user_login", "status": "passed", "duration": 0.52 },
        { "test_name": "payments::test_charge_creation", "status": "failed", "duration": 1.23, "error": "AssertionError: Expected status 200 but got 500" },
        { "test_name": "payments::test_refund_processing", "status": "passed", "duration": 0.89 },
        { "test_name": "notifications::test_email_sending", "status": "failed", "duration": 2.51, "error": "ConnectionRefusedError" }
      ]
    }
    

    Note that this creates a single input item for the next node.

  2. Add a Code node and connect it to the Set node. Set the Language to Python. You can leave the Mode as Run Once for All Items, since we only have one item to process.

  3. Enter and complete the following Python code. The goal is to produce a list of items, where each item represents one failed test.

    
    
    
    # Since we have only one input item containing the full report,
    # we can access it directly. _items will be a list with one element.
    report_item = _items[0]
    
    report_data = report_item['json']
    build_id = report_data.get('build_id')
    test_results = report_data.get('results', [])
    
    failed_tests = []
    
    
    
    
    # --- START YOUR CODE HERE ---
    
    
    
    
    # 1. Loop through the 'test_results' list.
    
    
    
    
    # 2. For each test, check if its 'status' is 'failed'.
    
    
    
    
    # 3. If it is a failed test, create a new dictionary for its JSON data.
    #    The new data should contain 'build_id', 'test_name', and 'error_details'.
    
    
    
    
    # 4. Append this new dictionary to the 'failed_tests' list,
    #    making sure to wrap it in the required {'json': ...} structure.
    
    
    
    
    # --- END YOUR CODE HERE ---
    
    
    
    
    # Return the list of failed tests. If none failed, this will be an empty list.
    return failed_tests
    
    Solution
    report_item = _items[0]
    
    report_data = report_item['json']
    build_id = report_data.get('build_id')
    test_results = report_data.get('results', [])
    
    failed_tests = []
    
    for test in test_results:
        if test.get('status') == 'failed':
            new_data = {
                'build_id': build_id,
                'test_name': test.get('test_name'),
                'error_details': test.get('error')
            }
            failed_tests.append({'json': new_data})
            
    return failed_tests
    
  4. Test the step. The output should be a list containing two items, one for test_charge_creation and one for test_email_sending, each structured correctly with a json key.


Conclusion

In this lesson, you've mastered the critical final step of working with the Python Code node: structuring your output. You are no longer limited to simple one-to-one data transformations. You now have the tools to precisely control the flow of data through your workflows.

Key Takeaways:

  • The Code node must always return a list of items.
  • Each item in the list must be a dictionary with a json key: [{'json': {...}}].
  • To filter items, simply omit them from the list you return. Returning [] is a valid way to stop a data flow path.
  • To split one item into many, return a list of new items. n8n will flatten the results into a single output list.
  • Your choice of iteration mode (All Items vs. Each Item) affects whether you construct and return the full list yourself or return single items for n8n to collect.

You are now fully equipped to handle data input, iteration, and output within the Code node. In our next lesson, we will combine all these skills to implement a more complex, practical data transformation, tackling a realistic CI/CD automation scenario from start to finish.