group objects by a field and sum another, then produce a CSV report

不羁岁月 提交于 2021-01-28 10:56:01

问题


How can I create a csv from this json? I have:

[
  {
    "name": "John",
    "cash": 5
  },
  {
    "name": "Anna",
    "cash": 4
  },
  {
    "name": "Anna",
    "cash": 3
  },
  {
    "name": "John",
    "cash": 8
  }
]

I need group by name and sum the cash and send the result a .csv like:

John,13
Anna,7

Thanks!


回答1:


JQ has group_by as a builtin, use that and do map(.cash) | add to sum cash values for each group.

group_by(.name)[] | [.[0].name, (map(.cash) | add)] | @csv

Online demo



来源:https://stackoverflow.com/questions/61953604/group-objects-by-a-field-and-sum-another-then-produce-a-csv-report

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!