Expressions & Variables
Expressions là "ngôn ngữ" bên trong n8n — cho phép bạn truy cập data từ nodes, transform values, và build dynamic logic.
🎯 Mục tiêu bài học
🎯 Mục tiêu
- Hiểu n8n expression syntax
- Truy cập data từ current và previous nodes
- Sử dụng built-in variables
- String, date, và number operations
Checkpoint
Expressions trong n8n là gì? Tại sao chúng quan trọng cho dynamic workflows?
📖 Expression Basics
1. Expression Basics
1.1 Syntax
1{{ expression }}2 3Ví dụ:4{{ $json.name }} → Truy cập field "name" của current item5{{ $json.user.email }} → Nested field6{{ $json.items[0].price }} → Array element7{{ "Hello " + $json.name }} → String concatenation1.2 Khi nào dùng Expression?
Mọi field trong n8n node đều có thể dùng expression (icon fx):
1✅ Dynamic values: {{ $json.email }}2✅ Calculations: {{ $json.price * 1.1 }}3✅ Conditions: {{ $json.age >= 18 ? "Adult" : "Minor" }}4✅ Templates: {{ "Dear " + $json.name + "," }}5✅ Date formatting: {{ $now.format('yyyy-MM-dd') }}Checkpoint
Cú pháp expression trong n8n là gì? Cho 3 ví dụ common expressions.
📊 Accessing Data
2. Accessing Data
2.1 Current Node Data
1{{ $json }} → Toàn bộ JSON object của current item2{{ $json.name }} → Field "name"3{{ $json.address.city }} → Nested object4{{ $json.tags[0] }} → First element of array5{{ $json.tags.length }} → Array length2.2 Previous Node Data
1{{ $('Node Name').item.json.fieldName }}2 3Ví dụ:4{{ $('Google Sheets').item.json.email }}5{{ $('HTTP Request').item.json.data.total }}6{{ $('Webhook').item.json.body.name }}2.3 All Items from Previous Node
1{{ $('Node Name').all() }} → All items as array2{{ $('Node Name').all().length }} → Number of items3{{ $('Node Name').first().json }} → First item4{{ $('Node Name').last().json }} → Last item2.4 Multiple Items
1// Khi node trả về nhiều items2{{ $json }} → Current item trong loop3{{ $itemIndex }} → Index of current item (0-based)4{{ $('Node').all()[2].json }} → Specific item by indexCheckpoint
Phân biệt $json, $('Node Name').item.json, và $('Node').all(). Khi nào dùng cái nào?
🔧 Built-in Variables
3. Built-in Variables
3.1 Execution Variables
| Variable | Description | Example |
|---|---|---|
$now | Current datetime | 2026-01-20T09:30:00 |
$today | Today's date | 2026-01-20 |
$itemIndex | Current item index | 0, 1, 2... |
$runIndex | Execution run number | 0 |
$workflow | Workflow metadata | $workflow.name |
$execution | Execution metadata | $execution.id |
$env | Environment variables | $env.API_KEY |
3.2 Date/Time
1{{ $now }} → 2026-01-20T09:30:00.000+07:002{{ $now.format('yyyy-MM-dd') }} → 2026-01-203{{ $now.format('HH:mm') }} → 09:304{{ $now.format('dd/MM/yyyy') }} → 20/01/20265{{ $now.minus(1, 'day') }} → Yesterday6{{ $now.plus(7, 'days') }} → Next week7{{ $now.startOf('month') }} → 2026-01-018{{ $now.endOf('month') }} → 2026-01-319{{ $today.weekday }} → 1 (Monday)3.3 Environment Variables
1Setup: n8n Settings → Variables2 API_KEY = "xxxxx"3 ENVIRONMENT = "production"4 5Access: {{ $env.API_KEY }}Checkpoint
Kể ra 5 built-in variables trong n8n và cho ví dụ sử dụng cho mỗi biến.
✂️ String Operations
4. String Operations
4.1 Basic String Methods
1{{ $json.name.toUpperCase() }} → "NGUYEN VAN A"2{{ $json.name.toLowerCase() }} → "nguyen van a"3{{ $json.email.trim() }} → Remove whitespace4{{ $json.text.slice(0, 100) }} → First 100 characters5{{ $json.name.replace('old', 'new') }} → Replace text6{{ $json.text.includes('keyword') }} → true/false7{{ $json.text.split(',') }} → Array from CSV8{{ $json.parts.join(', ') }} → Array to string4.2 Template Strings
1{{ `Dear ${$json.name},2 3Your order #${$json.orderId} has been shipped.4Estimated delivery: ${$json.deliveryDate}.5 6Thank you!` }}4.3 Conditional Text
1{{ $json.status === 'active' ? '🟢 Active' : '🔴 Inactive' }}2 3{{ $json.score >= 90 ? 'Excellent' 4 : $json.score >= 70 ? 'Good' 5 : 'Needs improvement' }}Checkpoint
Viết expression template string gửi email personalized với tên và orderId của khách hàng.
🔢 Number Operations
5. Number Operations
5.1 Math
1{{ $json.price * 1.1 }} → +10% tax2{{ $json.price * 0.8 }} → 20% discount3{{ Math.round($json.value) }} → Round4{{ Math.floor($json.value) }} → Round down5{{ Math.ceil($json.value) }} → Round up6{{ $json.total.toFixed(2) }} → "123.45" (2 decimals)7{{ Math.max($json.a, $json.b) }} → Larger value8{{ Math.min($json.a, $json.b) }} → Smaller value5.2 Aggregations
1// Sum all items' price2{{ $('Node').all().reduce((sum, item) => sum + item.json.price, 0) }}3 4// Average5{{ $('Node').all().reduce((sum, item) => sum + item.json.score, 0) / $('Node').all().length }}6 7// Count with condition8{{ $('Node').all().filter(item => item.json.status === 'active').length }}5.3 Currency Formatting
1{{ new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format($json.amount) }}2→ "1.500.000 ₫"3 4{{ new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format($json.amount) }}5→ "$1,500.00"Checkpoint
Viết expression tính tổng giá trị (sum) của tất cả items từ node trước. Dùng method nào?
📦 Object & Array Operations
6. Object & Array Operations
6.1 Object Access
1{{ Object.keys($json) }} → ["name", "email", "age"]2{{ Object.values($json.scores) }} → [85, 92, 78]3{{ Object.entries($json).length }} → Number of fields4{{ JSON.stringify($json) }} → Convert to string5{{ JSON.parse($json.jsonString) }} → Parse string to object6.2 Array Operations
1{{ $json.items.map(i => i.name) }} → Extract names2{{ $json.items.filter(i => i.price > 100) }} → Filter3{{ $json.items.find(i => i.id === 123) }} → Find one4{{ $json.items.sort((a, b) => a.price - b.price) }} → Sort5{{ $json.items.some(i => i.stock === 0) }} → Any out of stock?6{{ $json.items.every(i => i.price > 0) }} → All have price?7{{ [...new Set($json.categories)] }} → Unique values6.3 Spread & Merge
1// Merge objects2{{ { ...$json, status: 'processed', processedAt: $now } }}3 4// Flatten nested array5{{ $json.orders.flatMap(o => o.items) }}Checkpoint
Array method nào dùng để lọc items? Cho ví dụ filter items có price > 100.
🔁 Common Expression Patterns
7. Common Expression Patterns
7.1 Default Values
1{{ $json.name || 'Unknown' }} → Fallback if null/empty2{{ $json.phone ?? 'N/A' }} → Nullish coalescing7.2 Data Cleaning
1// Remove extra spaces2{{ $json.name.trim().replace(/\s+/g, ' ') }}3 4// Extract email domain5{{ $json.email.split('@')[1] }}6 7// Capitalize first letter8{{ $json.name.charAt(0).toUpperCase() + $json.name.slice(1) }}7.3 URL Building
1{{ `https://api.example.com/users/${$json.userId}/orders?status=${$json.status}&page=${$json.page}` }}7.4 Conditional Logic
1// Multiple conditions2{{ 3 $json.type === 'urgent' && $json.amount > 10000004 ? '#critical-alerts'5 : $json.type === 'urgent'6 ? '#alerts'7 : '#general'8}}8. Hands-on Lab
Lab 1: Data Formatting Pipeline
Build workflow:
- Google Sheets — Get raw data (names, emails, dates, amounts)
- Set node — Transform using expressions:
- Name: Title case
- Email: lowercase, trim
- Amount: VND format
- Date: dd/MM/yyyy format
- Slack — Post formatted summary
Lab 2: Dynamic Email Template
- Airtable — Get customer data
- Set node — Build email subject & body using expressions:
- Greet by name
- Show order details
- Calculate total with tax
- Conditional urgency message
- Email — Send personalized email
Lab 3: Report Generator
- HTTP Request — Get sales data API
- Expressions — Calculate:
- Total revenue (sum)
- Average order value
- Top product (max)
- MoM growth %
- Slack — Post report with emoji indicators
📝 Quiz
-
{{ $json.name }}truy cập gì?- Field "name" của current item
- Biến global
- Environment variable
- Workflow name
-
{{ $('Google Sheets').item.json.email }}dùng khi?- Truy cập current node
- Truy cập data từ node "Google Sheets" trước đó
- Gửi email
- Connect Google
-
{{ $json.price >= 1000 ? 'Premium' : 'Standard' }}trả về gì nếu price = 500?- Premium
- Standard
- Error
- 500
🎯 Key Takeaways
{{ }}— Expression syntax trong mọi n8n field$json— Current item data$('Node')— Access previous node data$now— Current datetime với format methods- JavaScript — Full JS support (strings, arrays, objects, math)
Checkpoint
Viết expression chọn Slack channel dựa trên type và amount của item (dùng conditional logic).
🚀 Bài tiếp theo
Data Transformation — Set, Merge, Split, Filter, và Sort nodes!
