json - 按两个字段分组并对每个组求和

标签 json csv jq

我有兴趣按总和对 jq 列进行分组。

我尝试过使用数组,但不行。我需要添加按级别和类型分组的学生。

我的json是这样的:

[
  {
    "name": "Maths",
    "Level": "One",
    "Genre": "Boys",
    "pupils": 5
  },
  {
    "name": "English",
    "Level": "Two",
    "Genre": "Boys",
    "pupils": 3
  },
  {
    "name": "Maths",
    "Level": "One",
    "Genre": "Girls",
    "pupils": 7
  },
  {
    "name": "English",
    "Level": "One",
    "Genre": "Girls",
    "pupils": 6
  },
  {
    "name": "Social",
    "Level": "One",
    "Genre": "Boys",
    "pupils": 4
  },
  {
    "name": "Social",
    "Level": "Two",
    "Genre": "Girls",
    "pupils": 0
  }
]

我需要转换为 csv,如下所示:

One, Boys, 9
One, Girls, 13
Two, Boys, 3
Two, Girls, 0

非常感谢!

最佳答案

这与 your previous question 非常相似。您只需在Level 之后按Genre 进行分组即可。

  group_by(.Level)[]
| group_by(.Genre)[]
| [.[0].Level, .[0].Genre, (map(.pupils) | add)]
| @csv

关于json - 按两个字段分组并对每个组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61969556/

相关文章:

Windows 窗体应用程序中的 C# 字符串缺少字符

c - 用`scanf()`读取逗号分隔的输入

json - 使用 jq 展平 JSON 文档

javascript - 获取天气预报数据以加载到 amcharts 数据加载器中

sql - 如何在mssql中使用左连接与json路径?

Java Jersey REST 请求参数清理

java - OpenCSV - CsvReaderNullFieldIndicator 似乎没有什么区别

json - 在jq中按多个键对降序进行排序

json - 将 JSON 文件中的所有时间戳转换为 bash 中的 unix 时间戳(Ubuntu)

php - 如何使用 jquery 调用 php Controller 方法?