表达式(Expressions)#
表达式是所有 n8n 节点中实现的强大功能。它们允许基于以下数据动态设置节点参数:
🌐 Expressions are a powerful feature implemented in all n8n nodes. They allow node parameters to be set dynamically based on data from:
- 先前节点执行次数
- 工作流
- 你的 n8n 环境
你还可以在表达式中执行 JavaScript,从而方便快捷地将数据转换为有用的参数值,而无需编写大量额外的代码。
🌐 You can also execute JavaScript within an expression, making this a convenient and easy way to manipulate data into useful parameter values without writing extensive extra code.
n8n 创建并使用一种名为 Tournament 的模板语言,并通过 自定义方法和变量 以及 数据转换函数 对其进行了扩展。这些功能使执行常见任务更容易,例如从其他节点获取数据或访问工作流元数据。
🌐 n8n created and uses a templating language called Tournament, and extends it with custom methods and variables and data transformation functions. These features make it easier to perform common tasks like getting data from other nodes or accessing workflow metadata.
n8n 还支持两个库:
🌐 n8n additionally supports two libraries:
n8n 中的数据
在编写表达式时,了解 n8n 中的数据结构和行为非常有用。有关在工作流中处理数据的更多信息,请参阅 数据。
编写表达式(Writing expressions)#
要使用表达式设置参数值:
🌐 To use an expression to set a parameter value:
- 将鼠标悬停在要使用表达式的参数上。
- 在 固定/表达式 切换中选择 表达式。
- 在参数中输入你的表达式,或选择 打开表达式编辑器
以打开表达式编辑器。如果使用表达式编辑器,你可以在 变量选择器 中浏览可用的数据。所有表达式的格式为 {{ your expression here }}。
示例:从 webhook 正文获取数据(Example: Get data from webhook body)#
考虑以下情景:你有一个通过 webhook 接收数据的 webhook 触发器。你想从中提取一些数据以在工作流中使用。
🌐 Consider the following scenario: you have a webhook trigger that receives data through the webhook body. You want to extract some of that data for use in the workflow.
你的 Webhook 数据类似于以下内容:
🌐 Your webhook data looks similar to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
在工作流的下一个节点中,你只想获取 city 的值。你可以使用以下表达式:
🌐 In the next node in the workflow, you want to get just the value of city. You can use the following expression:
1 | |
此表达式:
🌐 This expression:
- 使用 n8n 的自定义
$json变量访问传入的 JSON 格式数据。 - 查找
city的值(在此示例中为“纽约”)。请注意,此示例使用 JMESPath 语法来查询 JSON 数据。你也可以将此表达式写为{{$json['body']['city']}}。
示例:编写更长的 JavaScript(Example: Writing longer JavaScript)#
你可以在表达式中进行变量赋值或使用多个语句,但需要使用立即调用函数表达式 (IIFE) 的语法封装代码。
🌐 You can do things like variable assignments or multiple statements in an expression, but you need to wrap your code using the syntax for an IIFE (Immediately Invoked Function Expression).
以下代码使用 Luxon 日期和时间库来计算两个日期之间的月份数。我们将代码同时用大括号封装以形成表达式,并使用 IIFE 语法。
🌐 The following code use the Luxon date and time library to find the time between two dates in months. We surround the code in both the handlebar brackets for an expression and the IIFE syntax.
1 2 3 4 5 6 | |
常见问题(Common issues)#
有关常见错误或表达问题及建议的解决步骤,请参阅 常见问题。
🌐 For common errors or issues with expressions and suggested resolution steps, refer to Common Issues.