# JSONata

> Sommatic AI 在哪些地方使用 JSONata 而不是 JavaScript——data.transform，以及不带花括号的 flow.if 与 flow.switch 条件——如何引用字段和运行变量，以及容易踩坑的差异。

Source: https://docs.sommatic.ai/zh/expressions/jsonata/ (updated 2026-11-26)

JSONata 是一种用于 JSON 的查询与转换语言。Sommatic AI 在节点需要重组或检验输入的地方使用它：
映射、过滤和聚合都很简洁，而且无需包装函数。

## 使用 JSONata 的位置

| 节点                                                                      | 字段             | 何时                                   |
| ----------------------------------------------------------------------- | -------------- | ------------------------------------ |
| [`data.transform`](https://docs.sommatic.ai/zh/nodes/data.transform.md) | `expr`         | 始终使用，除非你写的是返回对象或列表的纯 JavaScript 表达式。 |
| [`flow.if`](https://docs.sommatic.ai/zh/nodes/flow.if.md)               | `expr`         | 文本中没有双花括号时。                          |
| [`flow.switch`](https://docs.sommatic.ai/zh/nodes/flow.switch.md)       | 每个分支条件的 `expr` | 文本中没有双花括号时。                          |

带双花括号时，这些字段改用 JavaScript [表达式](https://docs.sommatic.ai/zh/expressions.md)。

## 输入即上下文

JSONata 针对节点的输入求值，因此直接写字段名，无需 `$json`：

```text
customer.email
items[price > 50]
$sum(items.price)
```

`$$` 表示输入的根。运行变量需加双美元符号使用：`$$json`、`$$execution.id`、`$$workflow.slug`、`$$node.label`。
JSONata 中没有 `$('Node label')` 访问器：需要其他节点的输出时，请使用带花括号的 JavaScript 表达式，
或先把数据带入输入中。

## 转换数据

在 `data.transform` 中，`expr` 的结果会替换原有数据。用 JSONata 的对象语法构造新对象：

```text
{
  "order": id,
  "customer": customer.email,
  "lines": [items.{ "sku": sku, "total": qty * price }],
  "total": $sum(items.(qty * price)),
  "run": $$execution.id
}
```

需要列表时，请用 `[ … ]` 包裹路径：只有一个元素匹配时，JSONata 返回的是单个对象，而不是列表。

## 编写条件

在 `flow.if` 中，不带花括号的条件就是 JSONata：

```text
status = "active" and age >= 18
```

```text
$exists(customer.email) and $count(items) > 0
```

在 `flow.switch` 中，每个分支都有一个 JSONata `expr` 和它要打开的 `port`：

```json
{
  "cases": [
    { "expr": "category = \"billing\"", "port": "billing" },
    { "expr": "category = \"support\"", "port": "support" }
  ],
  "first_match": true
}
```

没有任何分支匹配时，`flow.switch` 从 `default` 端口离开。

## 与 JavaScript 的差异

| JSONata              | JavaScript        |
| -------------------- | ----------------- |
| `=` 和 `!=`           | `===` 和 `!==`     |
| `and`、`or`、`$not(…)` | JavaScript 的逻辑运算符 |
| 用 `&` 拼接字符串          | `+`               |
| 字符串使用双引号             | 单引号或双引号           |
| 缺失的字段只是为空            | 读取缺失字段的内部属性会抛出错误  |

> **注意: JSONata 中不存在 $json**
>
> 不带花括号的 `$json.age >= 18` 结果永远为 false：在 JSONata 中，`$json` 是未绑定的变量。请写成 `age >= 18`、
> `$$json.age >= 18`，或改用 JavaScript：`{{ $json.age >= 18 }}`。

JSONata 也有自己的日期函数，例如 `$now()`，它以 UTC 的 ISO 字符串返回当前时间。

## 参考

所有 JSONata 函数（`$sum`、`$count`、`$map`、`$filter`、`$string`、`$exists` 等）都列在
[JSONata 函数](https://docs.sommatic.ai/zh/expressions/jsonata-functions.md)参考中。

## 下一步

- [JSONata 函数](https://docs.sommatic.ai/zh/expressions/jsonata-functions.md): 完整的函数参考。
- [data.transform](https://docs.sommatic.ai/zh/nodes/data.transform.md): 转换节点的配置与端口。
