JSON解析-使用JQ按日期范围分组 [英] JSON parsing - group by date range with JQ

查看:466
本文介绍了JSON解析-使用JQ按日期范围分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON数据:

I have the following JSON data :

{
  "data": [  
    {"date": "2018-08-22","value": 1},
    {"date": "2018-08-30","value": 2},
    {"date": "2018-09-01","value": 3},
    {"date": "2018-09-22","value": 3},
    {"date": "2018-09-28","value": 4},
    {"date": "2018-10-18","value": 5},
    {"date": "2018-10-23","value": 6}
  ]
}

我想使用JQ每月从第一个值开始对数据进行分组: 我的月份是:

I would like to use JQ to group data per month starting at the first value : My month would be :

  • 2018 08 22至2018 09 21

  • 2018 08 22 to 2018 09 21

2018 09 22至2018 10 21

2018 09 22 to 2018 10 21

2018 10 22至2018 11 21

2018 10 22 to 2018 11 21

我的预期输出如下:

{
  "data": [  
    {"month": "2018-08-22 to 2018-09-21","sum": 6},
    {"month": "2018-09-22 to 2018-10-21","sum": 12},
    {"month": "2018-10-23 to 2018-11-21","sum": 6}
  ]
}

我该怎么做?

推荐答案

使用以下辅助函数可以轻松获得解决方案:

A solution is easily obtained with the following helper function:

# $day should be the day (an integer) that defines the cutoff point;
# input should be a Y-M-D string
def bucket($day):
  def prev: if .m > 1 then .m -= 1 else .m = 12 | .y -= 1 end;
  def fmt: if .m <= 9 then "\(.y)-0\(.m)" else "\(.y)-\(.m)" end;
  capture("(?<y>[0-9]+)-(?<m>[0-9]+)-(?<d>[0-9]+)")
  | map_values(tonumber)
  | if .d >= $day then . else prev end
  | fmt ;

我们现在计算存储桶数对:

We now compute the bucket-count pairs:

.data
| (.[0].date | capture("(?<d>[0-9]+)$") | .d | tonumber) as $day
| reduce .[] as $pair ({};
  .[$pair.date | bucket($day)] += ($pair.value) )

使用示例数据,将产生:

With the sample data, this produces:

{
  "2018-08": 6,
  "2018-09": 12,
  "2018-10": 6
}      

现在将其转换为所需的格式很简单,因此留作练习.

It is now a trivial matter to convert this into the desired format, and is thus left as an exercise.

这篇关于JSON解析-使用JQ按日期范围分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆