📦 Lesson 6 of 12  ·  N8N Automation

Working with Data &
JSON Transformations

N8N passes data between nodes as a structured array of items. Learn to add fields with the Set node, run custom JavaScript with the Code node, and combine data streams with the Merge node.

N8N Item Structure Set Node Code Node (JS) Merge Node Data Transformations

📝 N8N's Data Structure — The Items Array

Everything in N8N flows as an array of items. Each item is a JavaScript object with a json property containing your data. Understanding this structure is the foundation of building reliable workflows.

[ ]
Always an Array
{ }
Each Item = Object
json
Your Data Property

The N8N Items Array Format

JSON — N8N Items
// This is how N8N passes data between nodes
[
  {
    "json": {
      "name":  "Alice",
      "email": "alice@example.com",
      "role":  "admin"
    }
  },
  {
    "json": {
      "name":  "Bob",
      "email": "bob@example.com",
      "role":  "user"
    }
  }
]

When a node receives this array, it processes each item one at a time by default. If you have 10 items, the node runs 10 times — once for each. This is called "item looping" and it's automatic in N8N.

💡
Why the json Wrapper?
The json wrapper exists because N8N items can also carry binary data (files, images) alongside the JSON. This consistent structure lets N8N handle both types uniformly through the same pipeline.
📋
1 Item
A single record — one user, one order, one event. The most common case.
Single
📄
Many Items
An array of records all processed in parallel by the next node automatically.
Batch
💾
Binary Item
An item with both json metadata and binary data — for files, PDFs, and images.
File

⚙️ The Set Node — Add & Modify Fields

The Set node is your primary tool for adding new fields, renaming existing ones, removing fields, and reshaping your data structure. It's a no-code field mapper — you define what the output should look like and N8N does the rest.

Before and After the Set Node

▶ Input Data
firstName"Alice"
lastName"Smith"
email"alice@ex.com"
createdAt"2024-01-15"
internalId4892
▶ Output Data (after Set)
fullName"Alice Smith" ➕
email"alice@ex.com"
joinedYear2024 ➕
firstName, lastName, internalId removed
💡
Set Node Modes — "Keep Only Set" vs "Add Fields"
Toggle "Keep Only Set Fields" to strip all original data and return only what you defined. Leave it off to add new fields while keeping the original data intact. Both modes are useful depending on your goal.

Set Node Configuration — Common Patterns

N8N Set Node — Field Values
// Combine two string fields
fullName = {{ $json.firstName + ' ' + $json.lastName }}

// Normalize email to lowercase
email = {{ $json.email.toLowerCase() }}

// Extract year from date string
year = {{ new Date($json.createdAt).getFullYear() }}

// Static value (no expression needed)
source = "n8n-workflow"

// Conditional value using ternary
status = {{ $json.role === 'admin' ? 'active' : 'pending' }}

💻 The Code Node — Custom JavaScript

When the Set node isn't powerful enough, reach for the Code node. It gives you a full JavaScript environment to transform items with any logic you need — map, filter, reduce, fetch, compute — returning a new items array.

⚠️
The Code Node Must Always Return an Items Array
Your Code node must return an array like [{ json: {...} }, ...]. If you return a plain object or forget the json wrapper, N8N will throw an error. Each element must be an object with a json key.

Example: Transform and Enrich All Items

JavaScript — Code Node
// Transform all items flowing through this node
return items.map(item => ({
  json: {
    // Combine first + last name
    fullName: item.json.firstName + ' ' + item.json.lastName,

    // Normalize email to lowercase
    email: item.json.email.toLowerCase(),

    // Add a processing timestamp
    timestamp: new Date().toISOString(),

    // Calculate a score field
    score: item.json.points * 1.5,

    // Keep original email for reference
    originalEmail: item.json.email
  }
}));

More Code Node Patterns

JavaScript — Advanced Patterns
// Filter items — only keep active users
return items
  .filter(item => item.json.status === 'active')
  .map(item => ({ json: item.json }));

// Deduplicate by email address
const seen = new Set();
return items.filter(item => {
  if (seen.has(item.json.email)) return false;
  seen.add(item.json.email);
  return true;
});

// Sort items by date descending
return [...items].sort((a, b) =>
  new Date(b.json.createdAt) - new Date(a.json.createdAt)
);
🔨
Run Once vs Run Per Item
The Code node has two modes. "Run Once for All Items" gives you the full items array to manipulate — best for sorting, grouping, deduplication. "Run Once for Each Item" processes one item at a time with $input.item — best for per-record transformations.

🤝 Merge Node — Combining Data Streams

When your workflow splits into multiple branches (from an IF node, Switch node, or parallel API calls), the Merge node brings them back together. Choose the merge strategy based on what your data needs.

📋
Merge by Position
Pairs items from Input 1 and Input 2 by their index position. Item 0 from A + Item 0 from B = merged Item 0. Both inputs must have the same number of items.
Best for: Joining parallel enrichment calls
🔑
Merge by Key
Joins items that share a common field value — like an inner join in SQL. Specify a key (e.g. "userId") and N8N matches items from both inputs that have the same value for that key.
Best for: Enriching records with lookup data
📈
Append
Concatenates all items from Input 1 followed by all items from Input 2 into a single flat array. No joining logic — just combines both streams sequentially.
Best for: Rejoining split branches
Merge Node — Combining Two Branches
📈 Branch A
Users from DB
🌐 Branch B
Users from API
🤝 Merge Node
Append / Key / Position
✅ Combined Items
Single unified stream

🔄 Data Transformation Flow

A typical data pipeline in N8N flows data through a series of transformations before writing it to a destination. Here's the full picture:

Complete Data Transformation Pipeline
📤 Input Items
Raw API data
💻 Code Node
JS transform
⚙️ Set Node
Rename fields
🔄 Merge Node
Combine streams
📥 Output
Transformed items

Common Transformation Operations

🔨
Filter
Keep only items matching a condition
IF / Code
🔄
Map
Transform each item's shape
Set / Code
📊
Sort
Order items by field value
Sort / Code
📁
Group
Batch items by category
Code
🗑️
Dedupe
Remove duplicate records
Code / Remove Dup
📌
Format
Convert dates, numbers, strings
Set / Code
🧠 Quick Knowledge Check

1. What is an "item" in N8N's data model?

A A raw JSON string
B An object with a json property containing your data
C A node in the workflow canvas
D A single key-value pair

2. Which node lets you run custom JavaScript to transform data?

A Set Node
B HTTP Request Node
C Code Node
D Function Node

3. Which node combines two separate data streams into one?

A Split Out Node
B Set Node
C Merge Node
D IF Node
← Lesson 5: HTTP Requests & APIs