# Helpers

> 空值的默认值、slug、JMESPath 查询与 lodash。

Source: https://docs.sommatic.ai/zh/expressions/reference/helpers/

每个示例都在已部署的表达式引擎上、基于页面末尾的[示例上下文](#example-context)运行过。

## `$ifEmpty`

函数 · `any` · 来源: `Sommatic AI expression engine`

```javascript
$ifEmpty(value, fallback)
```

当 `value` 为 `undefined`、`null`、空字符串 `''`、空列表或没有键的对象时，返回 `fallback`。其他值原样返回：`0`、`false` 和全是空格的字符串都会保留。

### 参数

- `value` (any, 必填): 要检查的值，通常是可能缺失的读取结果。
- `fallback` (any, 必填): `value` 为空时返回的值。可为任意类型。

### 返回

`any`: `value` 或 `fallback`，保留各自的类型。

### 示例

空字符串会取 fallback。

```javascript
{{ $ifEmpty($json.body.priority, 'normal') }}
```

结果 (string):

```json
"normal"
```

```javascript
{{ $ifEmpty($json.body.customer.phone, 'no phone') }}
```

结果 (string):

```json
"no phone"
```

未执行的节点。

```javascript
{{ $ifEmpty($('Approval').item.json.decision, 'pending') }}
```

结果 (string):

```json
"pending"
```

0 不算空。

```javascript
{{ $ifEmpty(0, 10) }}
```

结果 (number):

```json
0
```

```javascript
{{ $ifEmpty([], ['none']) }}
```

结果 (list):

```json
[
  "none"
]
```

### 说明

- 若还要替换 `0` 或 `false`，请用 `||`：`{{ $json.body.retries || 3 }}`。若只替换 `null` 和 `undefined`，请用 `??`。

在 JSONata 中: `$$ifEmpty(body.priority, "normal")`

## `$slugify`

函数 · `string` · 来源: `lodash · kebabCase`

```javascript
$slugify(text)
```

将任意文本转换为 kebab case（lodash 的 `kebabCase`）：小写单词以连字符连接，去除重音符号，删除标点。在大小写变化处以及字母与数字之间也会拆分单词，因此 `helloWorld ABC123` 会变为 `hello-world-abc-123`。

### 参数

- `text` (any, 必填): 先转换为文本：`null` 变为 `'null'`。

### 返回

`string`: slug；文本为空时返回空字符串。

### 示例

```javascript
{{ $slugify('Hola Mundo Ñandú 2026') }}
```

结果 (string):

```json
"hola-mundo-nandu-2026"
```

```javascript
{{ $slugify($json.body.customer.name) }}
```

结果 (string):

```json
"ana-perez"
```

```javascript
{{ $slugify('helloWorld ABC123') }}
```

结果 (string):

```json
"hello-world-abc-123"
```

### 说明

- 先处理缺失值：`$slugify($ifEmpty($json.title, 'untitled'))`。

在 JSONata 中: `$$slugify(body.customer.name)`

## `$jmespath`

函数 · `any` · 来源: `jmespath · search`

```javascript
$jmespath(data, query)
```

对 `data` 执行 [JMESPath](/zh/expressions/jmespath/) 查询，返回其选中的内容：一个值、列表或对象。对于层级较深的响应，查询往往比等效的 JavaScript 更简短：过滤（`[?qty > \`0\`]`）、投影（`[*].sku`）和函数（`length`、`sort_by`、`max_by`）。查询中的字面量要放在反引号之间。

### 参数

- `data` (any, 必填): 要查询的值，通常是 `$json` 或某个节点的输出。
- `query` (string, 必填): JMESPath 表达式。请用单引号括起来，这样其中的反引号和双引号无需转义。

### 返回

`any`: 查询选中的内容；没有匹配时为 `null`。

### 示例

```javascript
{{ $jmespath($json.body, 'items[?qty > `0`].sku') }}
```

结果 (list):

```json
[
  "A-100",
  "C-300"
]
```

```javascript
{{ $jmespath($json.body, 'length(items)') }}
```

结果 (number):

```json
3
```

```javascript
{{ $jmespath($json.body, 'max_by(items, &price).sku') }}
```

结果 (string):

```json
"C-300"
```

```javascript
{{ $jmespath($json.body, 'items[*].{ id: sku, units: qty }') }}
```

结果 (list):

```json
[
  {
    "id": "A-100",
    "units": 2
  },
  {
    "id": "B-200",
    "units": 0
  },
  {
    "id": "C-300",
    "units": 1
  }
]
```

不存在的路径返回 null，而不是报错。

```javascript
{{ $jmespath($json.body, 'shipping.address.city') }}
```

结果 (null):

```json
null
```

不带反引号的字面量是语法错误。

```javascript
{{ $jmespath($json.body, 'items[?qty > 0]') }}
```

抛出:

```text
Invalid token (Number): "0"
```

### 错误

- `Invalid token (<type>): "<value>"`: 查询不是有效的 JMESPath，常见原因是数字或字符串字面量没有加反引号。

在 JSONata 中: `$$jmespath($$json, "body.items[0].sku")`

## `_`

库 · `lodash` · 来源: `lodash`

```javascript
_
```

完整的 [lodash](/zh/expressions/lodash/) 库。它是分组、求和、挑选字段、去重以及带默认值读取深层路径的最简洁方式。

### 示例

```javascript
{{ _.sumBy($json.body.items, 'qty') }}
```

结果 (number):

```json
3
```

```javascript
{{ _.uniq($json.body.tags) }}
```

结果 (list):

```json
[
  "new",
  "web"
]
```

```javascript
{{ _.get($json, 'body.shipping.city', 'unknown') }}
```

结果 (string):

```json
"unknown"
```

```javascript
{{ _.pick($json.body, ['order_id', 'email']) }}
```

结果 (object):

```json
{
  "order_id": "ord_1042",
  "email": "ana.perez@example.com"
}
```

```javascript
{{ _.keyBy($json.body.items, 'sku') }}
```

结果 (object):

```json
{
  "A-100": {
    "sku": "A-100",
    "qty": 2,
    "price": 10.5
  },
  "B-200": {
    "sku": "B-200",
    "qty": 0,
    "price": 4
  },
  "C-300": {
    "sku": "C-300",
    "qty": 1,
    "price": 25
  }
}
```

### 说明

- 每个函数的参数、返回值和示例见 [lodash 参考](/zh/expressions/lodash/)。

在 JSONata 中: JSONata 中不可用，它有自己的函数库。

## 示例上下文

示例基于以下数据运行：当前节点的输入（`$json`）、已运行的节点（`$(…)`）、本次运行的 ID 以及当前节点。时钟固定为 `2026-11-26T14:30:00.000Z`，服务器时区为 UTC，因此各页面中 `$now` 与 `$today` 的值都相同。

```json
{
  "$json": {
    "body": {
      "order_id": "ord_1042",
      "email": "ana.perez@example.com",
      "customer": {
        "name": "Ana Pérez",
        "segment": "gold"
      },
      "priority": "",
      "items": [
        {
          "sku": "A-100",
          "qty": 2,
          "price": 10.5
        },
        {
          "sku": "B-200",
          "qty": 0,
          "price": 4
        },
        {
          "sku": "C-300",
          "qty": 1,
          "price": 25
        }
      ],
      "tags": [
        "new",
        "web",
        "new"
      ],
      "created_at": "2026-11-25T09:15:00Z"
    },
    "headers": {
      "content-type": "application/json"
    },
    "query": {},
    "method": "POST"
  },
  "nodes": {
    "Webhook Receiver": "= $json",
    "Normalize input": {
      "correlation_id": "c-7f3a",
      "channel": "web"
    },
    "Classify": {
      "label": "billing",
      "confidence": 0.92
    }
  },
  "run": {
    "$flow_instance_result_id": "fir-xxxx",
    "$flow_instance_id": "fi-xxxx",
    "$flow_definition_id": "fd-xxxx",
    "$flow_version_id": "fv-xxxx",
    "$flow_slug": "order-intake"
  },
  "node": {
    "node_id": "node-notify",
    "label": "Notify customer"
  }
}
```

串联工作流的示例基于第二个上下文运行：一个由 `workflow.chain` 启动的工作流，其 `workflow.trigger` 节点的标签为 `Chain Entry Point`。

```json
{
  "$json": {
    "order_id": "ord_1042",
    "customer_email": "ana.perez@example.com",
    "amount": 46,
    "chain_context": {
      "caller_flow_definition_id": "fd-caller-xxxx",
      "caller_flow_instance_id": "fi-caller-xxxx",
      "caller_flow_slug": "order-intake",
      "caller_node_id": "node-chain-billing",
      "correlation_id": "chain-7Hq2Lw9sKd3pXa1mZr4t",
      "root_flow_instance_result_id": "fir-root-xxxx"
    }
  },
  "run": {
    "$flow_instance_result_id": "fir-hop-xxxx",
    "$flow_instance_id": "fi-hop-xxxx",
    "$flow_definition_id": "fd-billing-xxxx",
    "$flow_version_id": "fv-billing-xxxx",
    "$flow_slug": "billing-review",
    "$input": {
      "data": {
        "order_id": "ord_1042",
        "customer_email": "ana.perez@example.com",
        "amount": 46
      },
      "chain_context": {
        "caller_flow_definition_id": "fd-caller-xxxx",
        "caller_flow_instance_id": "fi-caller-xxxx",
        "caller_flow_slug": "order-intake",
        "caller_node_id": "node-chain-billing",
        "correlation_id": "chain-7Hq2Lw9sKd3pXa1mZr4t",
        "root_flow_instance_result_id": "fir-root-xxxx"
      }
    }
  },
  "node": {
    "node_id": "node-create-task",
    "label": "Create review task"
  }
}
```

示例运行所基于的编排器提交 31e874b.
