14.6. 高级 JSONata 功能
您可以通过应用各种高级功能(如阵列处理和内置功能),使用 JSONata 来更有效地转换事件。
14.6.1. 数组处理 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
JSONata 使得在事件有效负载中轻松处理阵列。您可以计算项目,根据条件过滤它们,并计算聚合值。
订购和计算总数处理项目示例
{
"specversion": "1.0",
"id": id,
"type": "order.processed",
"source": source,
"time": $now(),
"itemcount": $count(order.items),
"multiorder": $count(order.items) > 1,
"data": {
"order": order.id,
"items": order.items[quantity > 1].{
"product": name,
"quantity": quantity,
"lineTotal": price * quantity
},
"totalvalue": $sum(order.items.(price * quantity))
}
}
将其指定为输入:
{
"id": "12345",
"source": "https://example.com/orders",
"order": {
"id": "order-67890",
"items": [
{ "name": "Laptop", "price": 1000, "quantity": 1 },
{ "name": "Mouse", "price": 50, "quantity": 2 },
{ "name": "Keyboard", "price": 80, "quantity": 3 }
]
}
}
转换会生成以下输出:
{
"specversion": "1.0",
"id": "12345",
"type": "order.processed",
"source": "https://example.com/orders",
"time": "2025-03-03T09:13:23.753Z",
"itemcount": 3,
"multiorder": true,
"data": {
"order": "order-67890",
"items": [
{ "product": "Mouse", "quantity": 2, "lineTotal": 100 },
{ "product": "Keyboard", "quantity": 3, "lineTotal": 240 }
],
"totalvalue": 1340
}
}
在本例中:
-
$count (order.items)计算阵列中的项目数量。 -
过滤器
[quantity > 1]仅选择数量大于 1 的项目。 -
$sum (order.items. (price * quantity))计算总值。
14.6.2. 使用内置功能 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
JSONata 包括广泛的内置功能,可操作字符串、数字、日期和数组。这些功能可增强来自现有数据的新字段。
使用内置功能添加元数据的示例
{
"specversion": "1.0",
"id": id,
"type": "user.event",
"source": source,
"time": time,
"timestamp": $now(),
"username": $lowercase(data.user.name),
"initials": $join($map($split(data.user.name, " "), function($v) { $substring($v, 0, 1) }), ""),
"data": $
}
在本例中:
-
$now ()添加当前时间戳。 -
$lowercase ()将用户名转换为小写。 -
$split ()将名称分成多个部分,$map ()将每个字母提取,$join ()将它们组合成初始。