如何使用JSONata实现多字段分组并统计数量?
JSONata多字段分组统计数量实现方案
直接上干货,用示例数据演示具体实现:
示例输入数据
假设你的JSON数组结构如下:
[ {"category": "A", "status": "active", "value": 10}, {"category": "A", "status": "active", "value": 20}, {"category": "A", "status": "inactive", "value": 15}, {"category": "B", "status": "active", "value": 5}, {"category": "B", "status": "inactive", "value": 25}, {"category": "B", "status": "inactive", "value": 30} ]
方法1:使用$group() + $map()(直观易读)
先按多字段组合分组,再遍历分组统计数量,逻辑清晰适合新手:
$map( $group($, function($item) { // 定义分组依据的多字段 { "category": $item.category, "status": $item.status } }), function($group) { // 提取分组字段并统计数量 { "category": $group.category, "status": $group.status, "count": $count($group) } } )
方法2:使用$aggregate()(性能更优)
通过累加器构建唯一分组键,适合处理大数据量的场景:
$each( $aggregate($, function($acc, $item) { // 用分隔符拼接多字段生成唯一分组键 $key := $join([$item.category, $item.status], "|"); // 更新累加器中的分组统计数据 $acc{$key: { "category": $item.category, "status": $item.status, "count": $exists($acc{$key}) ? $acc{$key}.count + 1 : 1 }} }, {}), // 将分组对象转换为目标数组格式 function($value) { $value } )
最终输出结果
两种方法都会生成你需要的结构:
[ {"category": "A", "status": "active", "count": 2}, {"category": "A", "status": "inactive", "count": 1}, {"category": "B", "status": "active", "count": 1}, {"category": "B", "status": "inactive", "count": 2} ]
扩展说明
如果需要按更多字段分组,只需调整分组定义:
- 方法1:在
$group()的回调对象中新增字段(比如"type": $item.type) - 方法2:在
$join()的数组中新增字段(比如[$item.category, $item.status, $item.type])
内容的提问来源于stack exchange,提问作者jani_r
相关产品推荐
相关产品推荐

