【n8n教程】:掌握数据转换函数,轻松处理复杂数据

在n8n中,数据转换函数是最强大的工具之一。它们让你能够在表达式中快速处理和转换数据,无需编写复杂的JavaScript代码。无论你是在处理数组、字符串、日期还是数字,n8n都提供了便捷的内置函数,让数据处理变得轻松高效。

🎯 什么是数据转换函数?

数据转换函数是n8n提供的辅助函数,可以在表达式编辑器中直接使用,无需编写原生JavaScript代码。它们遵循统一的语法模式:


    
    
    
  // 基础语法
{{ $json.fieldName.functionName() }}

// 带参数的函数

{{ $json.array.chunk(5) }}

// 链式调用

{{ $json.string.toUpperCase().trim() }}

优势


📊 数据转换函数分类详解

1️⃣ 数组函数(Array Functions)

数组是n8n中最常用的数据结构。以下是核心数组函数:

函数功能使用场景示例
first()获取第一个元素取出列表中的首项{{ $json.items.first() }}
last()获取最后一个元素取出列表中的末项{{ $json.items.last() }}
length()获取数组长度统计列表数量{{ $json.items.length }}
isEmpty()检查是否为空数据验证{{ $json.items.isEmpty() }}
average()计算平均值数值统计{{ $json.scores.average() }}
sum()计算总和数值求和{{ $json.prices.sum() }}
max()获取最大值找最大值{{ $json.numbers.max() }}
min()获取最小值找最小值{{ $json.numbers.min() }}
chunk(size)按大小分组批量处理数据{{ $json.items.chunk(10) }}
compact()移除空值清理数据{{ $json.items.compact() }}
unique()去重数据去重{{ $json.tags.unique() }}
removeDuplicates()按字段去重高级去重{{ $json.users.removeDuplicates('id') }}
pluck(field)提取字段取特定列数据{{ $json.users.pluck('email') }}
randomItem()随机取一个随机抽样{{ $json.items.randomItem() }}
difference(arr)找差异对比两个数组{{ $json.arr1.difference(arr2) }}
intersection(arr)取交集找公共元素{{ $json.arr1.intersection(arr2) }}
union(arr)合并去重合并数组{{ $json.arr1.union(arr2) }}
merge(arr)合并对象数组合并属性{{ $json.users.merge(newUsers) }}

💡 实战例子


    
    
    
  // 场景:有一个订单列表,需要计算总金额和订单数量
{{ $json.orders.sum() }}  // 计算所有订单金额总和
{{ $json.orders.length }} // 统计订单总数
{{ $json.orders.first() }} // 获取第一个订单

// 场景:清理重复的标签

{{ $json.tags.removeDuplicates() }}

// 场景:获取前10条数据

{{ $json.items.chunk(10).first() }}

2️⃣ 字符串函数(String Functions)

字符串处理是数据转换的重要环节:

函数功能使用场景示例
toUpperCase()转大写标准化格式{{ $json.name.toUpperCase() }}
toLowerCase()转小写标准化格式{{ $json.email.toLowerCase() }}
toTitleCase()标题格式格式美化{{ $json.title.toTitleCase() }}
toSentenceCase()句子格式格式美化{{ $json.text.toSentenceCase() }}
toSnakeCase()蛇形命名编程规范{{ $json.fieldName.toSnakeCase() }}
isEmpty()检查为空数据验证{{ $json.name.isEmpty() }}
isNotEmpty()检查非空数据验证{{ $json.name.isNotEmpty() }}
isEmail()是否邮箱邮箱验证{{ $json.email.isEmail() }}
isUrl()是否网址URL验证{{ $json.link.isUrl() }}
isNumeric()是否数字数值检测{{ $json.code.isNumeric() }}
isDomain()是否域名域名验证{{ $json.domain.isDomain() }}
extractEmail()提取邮箱从文本提取邮箱{{ $json.text.extractEmail() }}
extractUrl()提取网址从文本提取URL{{ $json.content.extractUrl() }}
extractDomain()提取域名从URL提取域名{{ $json.url.extractDomain() }}
extractUrlPath()提取路径从URL提取路径{{ $json.url.extractUrlPath() }}
base64Encode()Base64编码数据加密{{ $json.data.base64Encode() }}
base64Decode()Base64解码数据解密{{ $json.encoded.base64Decode() }}
urlEncode()URL编码创建URL参数{{ $json.text.urlEncode() }}
urlDecode()URL解码解析URL参数{{ $json.encoded.urlDecode() }}
removeTags()移除标签清理HTML{{ $json.html.removeTags() }}
removeMarkdown()移除Markdown清理格式{{ $json.text.removeMarkdown() }}
replaceSpecialChars()替换特殊符号规范化文本{{ $json.text.replaceSpecialChars() }}
quote()添加引号格式化输出{{ $json.text.quote() }}
parseJson()解析JSONJSON转换{{ $json.json_string.parseJson() }}
toJsonString()转JSON字符串对象序列化{{ $json.object.toJsonString() }}
toInt()转整数类型转换{{ $json.number_str.toInt() }}
toFloat()转浮点数类型转换{{ $json.number_str.toFloat() }}
toWholeNumber()转整数类型转换{{ $json.amount.toWholeNumber() }}
toBoolean()转布尔值类型转换{{ $json.status.toBoolean() }}
toDateTime()转日期对象日期转换{{ $json.date_str.toDateTime() }}
hash(algo)哈希处理数据加密{{ $json.password.hash('sha256') }}

💡 实战例子


    
    
    
  // 场景:标准化用户邮箱
{{ $json.email.toLowerCase().trim() }}

// 场景:验证并提取邮箱

{{ $json.text.isEmail() ? $json.text : $json.text.extractEmail() }}

// 场景:从URL提取域名

{{ $json.website_url.extractDomain() }}

// 场景:清理网页内容

{{ $json.html_content.removeTags().removeMarkdown() }}

// 场景:对敏感数据进行加密

{{ $json.password.hash('sha256') }}

3️⃣ 数字函数(Number Functions)

数字处理在金融、统计等领域至关重要:

函数功能使用场景示例
round(places)四舍五入精度控制{{ $json.price.round(2) }}
ceil()向上取整向上舍入{{ $json.price.ceil() }}
floor()向下取整向下舍入{{ $json.price.floor() }}
isEven()是否偶数奇偶判断{{ $json.num.isEven() }}
isOdd()是否奇数奇偶判断{{ $json.num.isOdd() }}
toBoolean()转布尔值类型转换{{ $json.status.toBoolean() }}
toDateTime(fmt)转日期时间戳转日期{{ $json.timestamp.toDateTime('ms') }}
format(locale)格式化多语言格式{{ $json.price.format('en-US') }}

💡 实战例子


    
    
    
  // 场景:商品价格精确到两位小数
{{ $json.price.round(2) }}

// 场景:库存管理,检查是否偶数

{{ $json.quantity.isEven() ? '可分成对' : '不能完全分对' }}

// 场景:将时间戳转为日期

{{ $json.created_timestamp.toDateTime('ms').format('YYYY-MM-DD') }}

// 场景:多语言货币格式

{{ $json.amount.format('zh-CN') }}  // 中文格式
{{ $json.amount.format('en-US') }}  // 美国格式

4️⃣ 日期函数(Date Functions)

日期处理对于工作流自动化至关重要:

函数功能使用场景示例
format(fmt)格式化日期日期展示{{ $json.date.format('YYYY-MM-DD') }}
plus(n, unit)增加时间计算截止日期{{ $json.date.plus(7, 'days') }}
minus(n, unit)减少时间计算历史日期{{ $json.date.minus(1, 'months') }}
extract(unit)提取时间部分获取年月日{{ $json.date.extract('year') }}
beginningOf(unit)时期开始计算时期起点{{ $json.date.beginningOf('month') }}
endOfMonth()月底计算月底日期{{ $json.date.endOfMonth() }}
isBetween(d1, d2)在时间范围内时间验证{{ $json.date.isBetween(date1, date2) }}
isWeekend()是否周末工作日检测{{ $json.date.isWeekend() }}
isDst()是否夏令时时区处理{{ $json.date.isDst() }}
isInLast(n, unit)在最近时间内时间范围检测{{ $json.date.isInLast(7, 'days') }}

💡 实战例子


    
    
    
  // 场景:创建7天后的截止日期
{{ $json.order_date.plus(7, 'days').format('YYYY-MM-DD') }}

// 场景:检查订单是否在最近30天内

{{ $json.order_date.isInLast(30, 'days') ? '最近订单' : '历史订单' }}

// 场景:检查是否周末(决定发送邮件的时间)

{{ $json.date.isWeekend() ? '下周一发送' : '今天发送' }}

// 场景:提取年份进行分类

{{ $json.date.extract('year') }}

// 场景:获取月底日期进行结账

{{ $json.date.endOfMonth().format('YYYY-MM-DD') }}

5️⃣ 布尔值函数(Boolean Functions)

布尔值用于逻辑判断和条件流控制:

函数功能使用场景示例
toInt()转整数类型转换{{ $json.active.toInt() }}

💡 实战例子


    
    
    
  // 场景:将活跃状态转为数字(1=活跃,0=非活跃)
{{ $json.is_active.toInt() }}

// 场景:条件判断

{{ $json.is_premium.toInt() === 1 ? '高级用户' : '普通用户' }}

6️⃣ 对象函数(Object Functions)

对象是n8n中的关键数据结构:

函数功能使用场景示例
isEmpty()检查为空对象验证{{ $json.data.isEmpty() }}
hasField(name)有无字段字段检测{{ $json.user.hasField('email') }}
removeField(key)移除字段数据清理{{ $json.user.removeField('password') }}
removeFieldsContaining(val)移除含值字段批量删除{{ $json.data.removeFieldsContaining('null') }}
keepFieldsContaining(val)保留含值字段数据提取{{ $json.data.keepFieldsContaining('active') }}
compact()移除空值数据清理{{ $json.data.compact() }}
merge(obj)合并对象对象组合{{ $json.user.merge(profile) }}
toJsonString()转JSON字符串序列化{{ $json.data.toJsonString() }}
urlEncode()URL编码生成URL参数{{ $json.params.urlEncode() }}

💡 实战例子


    
    
    
  // 场景:检查必需字段是否存在
{{ $json.form.hasField('email') && $json.form.hasField('name') }}

// 场景:从对象中移除敏感信息

{{ $json.user.removeField('password').removeField('secret_key') }}

// 场景:合并用户基本信息和补充信息

{{ $json.user_base.merge(user_profile) }}

// 场景:将对象转为URL查询参数

{{ $json.filters.urlEncode() }}  // { search: 'test', limit: 10 } => 'search=test&limit=10'

// 场景:清理对象中的空值

{{ $json.data.compact() }}

🚀 实战工作流:客户数据处理与分析

现在让我们通过一个完整的实际工作流示例,展示如何综合运用这些数据转换函数。

工作流场景

处理从CRM系统导入的客户数据,包括:

完整工作流代码

将以下JSON代码导入n8n,即可快速创建该工作流:


    
    
    
  {
  "name"
: "Customer Data Processing & Analytics",
  "nodes"
: [
    {

      "parameters"
: {
        "content"
: "[\n  {\n    \"id\": 1,\n    \"name\": \"John Smith\",\n    \"email\": \"  JOHN.SMITH@GMAIL.COM  \",\n    \"phone\": \"(555) 123-4567\",\n    \"status\": \"active\",\n    \"purchase_amount\": 1500.567,\n    \"purchase_date\": \"2025-01-15\",\n    \"tags\": [\"vip\", \"repeat\", \"vip\", \"premium\"]\n  },\n  {\n    \"id\": 2,\n    \"name\": \"jane doe\",\n    \"email\": \"jane.doe@HOTMAIL.COM\",\n    \"phone\": \"\",\n    \"status\": \"inactive\",\n    \"purchase_amount\": 750.25,\n    \"purchase_date\": \"2024-12-20\",\n    \"tags\": [\"new\", \"newsletter\"]\n  },\n  {\n    \"id\": 3,\n    \"name\": \"bob johnson\",\n    \"email\": \"bob@example.com\",\n    \"phone\": \"(555) 987-6543\",\n    \"status\": \"active\",\n    \"purchase_amount\": 2250.99,\n    \"purchase_date\": \"2025-01-10\",\n    \"tags\": [\"enterprise\", \"vip\", \"contract\"]\n  }\n]"
      }
,
      "name"
: "Sample Data",
      "type"
: "n8n-nodes-base.function",
      "typeVersion"
: 1,
      "position"
: [300, 300]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ $json.name.toTitleCase() }}"
      }
,
      "name"
: "Standardize Names",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [500, 200]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ $json.email.toLowerCase().trim() }}"
      }
,
      "name"
: "Clean Email",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [700, 200]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ $json.purchase_amount.round(2) }}"
      }
,
      "name"
: "Round Amount",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [900, 200]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ $json.tags.removeDuplicates().toJsonString() }}"
      }
,
      "name"
: "Remove Duplicate Tags",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [1100, 200]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ { id: $json.id, name: $json.name, email: $json.email, is_valid: $json.email.isEmail(), status: $json.status, purchase_amount: $json.purchase_amount, purchase_date: $json.purchase_date, tag_count: $json.tags.length, is_vip: $json.tags.includes('vip'), days_since_purchase: $json.purchase_date.toDateTime().extract('day') } }}"
      }
,
      "name"
: "Build Customer Profile",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [1300, 200]
    }
,
    {

      "parameters"
: {
        "conditions"
: {
          "string"
: [
            {

              "value1"
: "={{ $json.is_valid }}",
              "value2"
: "true",
              "operation"
: "equal"
            }

          ]

        }

      }
,
      "name"
: "Filter Valid Emails",
      "type"
: "n8n-nodes-base.if",
      "typeVersion"
: 2,
      "position"
: [1500, 100]
    }
,
    {

      "parameters"
: {
        "mode"
: "each",
        "expression"
: "={{ { ...($json), customer_tier: $json.purchase_amount > 2000 ? 'Platinum' : $json.purchase_amount > 1000 ? 'Gold' : 'Silver', last_purchase_days: 'recent' } }}"
      }
,
      "name"
: "Classify Customers",
      "type"
: "n8n-nodes-base.set",
      "typeVersion"
: 3.4,
      "position"
: [1500, 250]
    }
,
    {

      "parameters"
: {
        "content"
: "PROCESSING SUMMARY:\n\nTotal Customers Processed: {{ $json.length }}\n\nData Quality Metrics:\n- Valid Emails: {{ $json.filter(c => c.is_valid).length }}\n- VIP Customers: {{ $json.filter(c => c.is_vip).length }}\n- Total Revenue: ${{ $json.map(c => c.purchase_amount).sum().round(2) }}\n- Average Purchase: ${{ $json.map(c => c.purchase_amount).average().round(2) }}\n- Max Purchase: ${{ $json.map(c => c.purchase_amount).max().round(2) }}\n- Min Purchase: ${{ $json.map(c => c.purchase_amount).min().round(2) }}\n\nCustomer Tiers:\n- Platinum: {{ $json.filter(c => c.customer_tier === 'Platinum').length }}\n- Gold: {{ $json.filter(c => c.customer_tier === 'Gold').length }}\n- Silver: {{ $json.filter(c => c.customer_tier === 'Silver').length }}"
      }
,
      "name"
: "Generate Report",
      "type"
: "n8n-nodes-base.debug",
      "typeVersion"
: 1,
      "position"
: [1700, 200]
    }

  ]
,
  "connections"
: {
    "Sample Data"
: {
      "main"
: [
        [

          {

            "node"
: "Standardize Names",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Standardize Names"
: {
      "main"
: [
        [

          {

            "node"
: "Clean Email",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Clean Email"
: {
      "main"
: [
        [

          {

            "node"
: "Round Amount",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Round Amount"
: {
      "main"
: [
        [

          {

            "node"
: "Remove Duplicate Tags",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Remove Duplicate Tags"
: {
      "main"
: [
        [

          {

            "node"
: "Build Customer Profile",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Build Customer Profile"
: {
      "main"
: [
        [

          {

            "node"
: "Filter Valid Emails",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Filter Valid Emails"
: {
      "main"
: [
        [

          {

            "node"
: "Classify Customers",
            "type"
: "main",
            "index"
: 0
          }

        ]
,
        [

          {

            "node"
: "Classify Customers",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }
,
    "Classify Customers"
: {
      "main"
: [
        [

          {

            "node"
: "Generate Report",
            "type"
: "main",
            "index"
: 0
          }

        ]

      ]

    }

  }

}

工作流说明

📍 工作流步骤

  1. 1. Sample Data - 示例数据源,包含3个客户的原始数据
  2. 2. Standardize Names - 使用 toTitleCase() 将名字转为标题格式
  3. 3. Clean Email - 使用 toLowerCase()trim() 清理邮箱
  4. 4. Round Amount - 使用 round(2) 将金额精确到两位小数
  5. 5. Remove Duplicate Tags - 使用 removeDuplicates() 去除重复标签
  6. 6. Build Customer Profile - 构建客户档案,使用多个函数
  7. 7. Filter Valid Emails - 使用 isEmail() 验证邮箱有效性
  8. 8. Classify Customers - 根据消费金额分类(Platinum/Gold/Silver)
  9. 9. Generate Report - 生成统计报告

关键函数使用总结

该工作流演示了以下核心数据转换函数:


💡 最佳实践

✅ 推荐做法

  1. 1. 链式调用 - 一次处理多个转换,提高效率
    
        
        
        
      {{ $json.email.toLowerCase().trim().isEmail() }}
  2. 2. 验证数据 - 在使用前检查数据有效性
    
        
        
        
      {{ $json.email.isEmail() ? $json.email : 'invalid' }}
  3. 3. 使用条件判断 - 根据数据内容做出决定
    
        
        
        
      {{ $json.amount > 1000 ? 'VIP' : 'Regular' }}
  4. 4. 整理输出 - 使用 compact()removeField() 清理最终结果
    
        
        
        
      {{ $json.data.compact().removeField('internal_id') }}

❌ 避免陷阱

  1. 1. 不检查空值 - 空值可能导致错误
    
        
        
        
      // ❌ 错误
    {{ $json.array.first() }}

    // ✅ 正确

    {{ $json.array.isEmpty() ? null : $json.array.first() }}
  2. 2. 忘记类型转换 - 不同类型的数据需要转换
    
        
        
        
      // ❌ 错误(字符串数字相加)
    {{ $json.price + $json.tax }}

    // ✅ 正确

    {{ ($json.price.toFloat() + $json.tax.toFloat()).round(2) }}
  3. 3. 过度嵌套 - 复杂表达式难以维护,使用多个Set节点
    
        
        
        
      // ❌ 不建议
    {{ $json.users.map(u => u.email).filter(e => e.isEmail()).unique().join(';') }}

    // ✅ 建议用多个Set节点分步进行

总结

n8n的数据转换函数是处理数据的强大工具。通过掌握这些函数,你可以:


引用链接

[1] 官方文档: https://docs.n8n.io/code/builtin/data-transformation-functions/
[2] n8n系列教程: https://www.undsky.com/blog/?category=n8n%E6%95%99%E7%A8%8B#