MinAI - Về trang chủ
Hướng dẫn
9/1340 phút
Đang tải...

Expressions & Variables

Master n8n expressions để truy cập data, transform values, và build dynamic workflows

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.

0

🎯 Mục tiêu bài học

TB5 min

🎯 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?

1

📖 Expression Basics

TB5 min

1. Expression Basics

1.1 Syntax

Ví dụ
1{{ expression }}
2
3Ví dụ:
4{{ $json.name }} → Truy cập field "name" của current item
5{{ $json.user.email }} → Nested field
6{{ $json.items[0].price }} → Array element
7{{ "Hello " + $json.name }} → String concatenation

1.2 Khi nào dùng Expression?

Mọi field trong n8n node đều có thể dùng expression (icon fx):

Ví dụ
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.

2

📊 Accessing Data

TB5 min

2. Accessing Data

2.1 Current Node Data

Ví dụ
1{{ $json }} → Toàn bộ JSON object của current item
2{{ $json.name }} → Field "name"
3{{ $json.address.city }} → Nested object
4{{ $json.tags[0] }} → First element of array
5{{ $json.tags.length }} → Array length

2.2 Previous Node Data

Ví dụ
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

Ví dụ
1{{ $('Node Name').all() }} → All items as array
2{{ $('Node Name').all().length }} → Number of items
3{{ $('Node Name').first().json }} → First item
4{{ $('Node Name').last().json }} → Last item

2.4 Multiple Items

Ví dụ
1// Khi node trả về nhiều items
2{{ $json }} → Current item trong loop
3{{ $itemIndex }} → Index of current item (0-based)
4{{ $('Node').all()[2].json }} → Specific item by index

Checkpoint

Phân biệt $json, $('Node Name').item.json, và $('Node').all(). Khi nào dùng cái nào?

3

🔧 Built-in Variables

TB5 min

3. Built-in Variables

3.1 Execution Variables

VariableDescriptionExample
$nowCurrent datetime2026-01-20T09:30:00
$todayToday's date2026-01-20
$itemIndexCurrent item index0, 1, 2...
$runIndexExecution run number0
$workflowWorkflow metadata$workflow.name
$executionExecution metadata$execution.id
$envEnvironment variables$env.API_KEY

3.2 Date/Time

Ví dụ
1{{ $now }} → 2026-01-20T09:30:00.000+07:00
2{{ $now.format('yyyy-MM-dd') }} → 2026-01-20
3{{ $now.format('HH:mm') }} → 09:30
4{{ $now.format('dd/MM/yyyy') }} → 20/01/2026
5{{ $now.minus(1, 'day') }} → Yesterday
6{{ $now.plus(7, 'days') }} → Next week
7{{ $now.startOf('month') }} → 2026-01-01
8{{ $now.endOf('month') }} → 2026-01-31
9{{ $today.weekday }} → 1 (Monday)

3.3 Environment Variables

Ví dụ
1Setup: n8n Settings → Variables
2 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.

4

✂️ String Operations

TB5 min

4. String Operations

4.1 Basic String Methods

Ví dụ
1{{ $json.name.toUpperCase() }} → "NGUYEN VAN A"
2{{ $json.name.toLowerCase() }} → "nguyen van a"
3{{ $json.email.trim() }} → Remove whitespace
4{{ $json.text.slice(0, 100) }} → First 100 characters
5{{ $json.name.replace('old', 'new') }} → Replace text
6{{ $json.text.includes('keyword') }} → true/false
7{{ $json.text.split(',') }} → Array from CSV
8{{ $json.parts.join(', ') }} → Array to string

4.2 Template Strings

Ví dụ
1{{ `Dear ${$json.name},
2
3Your order #${$json.orderId} has been shipped.
4Estimated delivery: ${$json.deliveryDate}.
5
6Thank you!` }}

4.3 Conditional Text

Ví dụ
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.

5

🔢 Number Operations

TB5 min

5. Number Operations

5.1 Math

Ví dụ
1{{ $json.price * 1.1 }} → +10% tax
2{{ $json.price * 0.8 }} → 20% discount
3{{ Math.round($json.value) }} → Round
4{{ Math.floor($json.value) }} → Round down
5{{ Math.ceil($json.value) }} → Round up
6{{ $json.total.toFixed(2) }} → "123.45" (2 decimals)
7{{ Math.max($json.a, $json.b) }} → Larger value
8{{ Math.min($json.a, $json.b) }} → Smaller value

5.2 Aggregations

Ví dụ
1// Sum all items' price
2{{ $('Node').all().reduce((sum, item) => sum + item.json.price, 0) }}
3
4// Average
5{{ $('Node').all().reduce((sum, item) => sum + item.json.score, 0) / $('Node').all().length }}
6
7// Count with condition
8{{ $('Node').all().filter(item => item.json.status === 'active').length }}

5.3 Currency Formatting

Ví dụ
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?

6

📦 Object & Array Operations

TB5 min

6. Object & Array Operations

6.1 Object Access

Ví dụ
1{{ Object.keys($json) }} → ["name", "email", "age"]
2{{ Object.values($json.scores) }} → [85, 92, 78]
3{{ Object.entries($json).length }} → Number of fields
4{{ JSON.stringify($json) }} → Convert to string
5{{ JSON.parse($json.jsonString) }} → Parse string to object

6.2 Array Operations

Ví dụ
1{{ $json.items.map(i => i.name) }} → Extract names
2{{ $json.items.filter(i => i.price > 100) }} → Filter
3{{ $json.items.find(i => i.id === 123) }} → Find one
4{{ $json.items.sort((a, b) => a.price - b.price) }} → Sort
5{{ $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 values

6.3 Spread & Merge

Ví dụ
1// Merge objects
2{{ { ...$json, status: 'processed', processedAt: $now } }}
3
4// Flatten nested array
5{{ $json.orders.flatMap(o => o.items) }}

Checkpoint

Array method nào dùng để lọc items? Cho ví dụ filter items có price > 100.

7

🔁 Common Expression Patterns

TB5 min

7. Common Expression Patterns

7.1 Default Values

Ví dụ
1{{ $json.name || 'Unknown' }} → Fallback if null/empty
2{{ $json.phone ?? 'N/A' }} → Nullish coalescing

7.2 Data Cleaning

Ví dụ
1// Remove extra spaces
2{{ $json.name.trim().replace(/\s+/g, ' ') }}
3
4// Extract email domain
5{{ $json.email.split('@')[1] }}
6
7// Capitalize first letter
8{{ $json.name.charAt(0).toUpperCase() + $json.name.slice(1) }}

7.3 URL Building

Ví dụ
1{{ `https://api.example.com/users/${$json.userId}/orders?status=${$json.status}&page=${$json.page}` }}

7.4 Conditional Logic

Ví dụ
1// Multiple conditions
2{{
3 $json.type === 'urgent' && $json.amount > 1000000
4 ? '#critical-alerts'
5 : $json.type === 'urgent'
6 ? '#alerts'
7 : '#general'
8}}

8. Hands-on Lab

Lab 1: Data Formatting Pipeline

Build workflow:

  1. Google Sheets — Get raw data (names, emails, dates, amounts)
  2. Set node — Transform using expressions:
    • Name: Title case
    • Email: lowercase, trim
    • Amount: VND format
    • Date: dd/MM/yyyy format
  3. Slack — Post formatted summary

Lab 2: Dynamic Email Template

  1. Airtable — Get customer data
  2. Set node — Build email subject & body using expressions:
    • Greet by name
    • Show order details
    • Calculate total with tax
    • Conditional urgency message
  3. Email — Send personalized email

Lab 3: Report Generator

  1. HTTP Request — Get sales data API
  2. Expressions — Calculate:
    • Total revenue (sum)
    • Average order value
    • Top product (max)
    • MoM growth %
  3. Slack — Post report with emoji indicators

📝 Quiz

  1. {{ $json.name }} truy cập gì?

    • Field "name" của current item
    • Biến global
    • Environment variable
    • Workflow name
  2. {{ $('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
  3. {{ $json.price >= 1000 ? 'Premium' : 'Standard' }} trả về gì nếu price = 500?

    • Premium
    • Standard
    • Error
    • 500

🎯 Key Takeaways

  1. {{ }} — Expression syntax trong mọi n8n field
  2. $json — Current item data
  3. $('Node') — Access previous node data
  4. $now — Current datetime với format methods
  5. 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!