json - JSON 解析 - 使用 JQ 按日期范围分组
问题描述
我有以下 JSON 数据:
{
"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 从第一个值开始每月对数据进行分组:我的月份是:
2018年08月22日至2018年09月21日
2018 年 9 月 22 日至 2018 年 10 月 21 日
2018 年 10 月 22 日至 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}
]
}
我怎样才能做到这一点 ?
解决方案
使用以下辅助函数很容易获得解决方案:
# $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 ;
我们现在计算桶数对:
.data
| (.[0].date | capture("(?<d>[0-9]+)$") | .d | tonumber) as $day
| reduce .[] as $pair ({};
.[$pair.date | bucket($day)] += ($pair.value) )
使用样本数据,这会产生:
{
"2018-08": 6,
"2018-09": 12,
"2018-10": 6
}
现在将其转换为所需的格式是一件小事,因此留作练习。
推荐阅读
- c# - C# 新字符串 [2] 与新字符串 []
- mongodb - 如何在 .Net Core Model 上自定义 MongoDb 集合名称?
- grpc - `Any` 和 `Duration` 类型未定义
- java - 具有组计数 gremlin 查询的子句
- javascript - 为什么我在 crypto-js 上收到格式错误的 UTF-8 数据错误?
- oop - 为什么我不能在delphi中做到这一点?我必须得到这个错误吗?[异常 EAccessViolation]
- mysql - 如何使用laravel过滤pdf中的数据?
- keyboard-shortcuts - 如何在 Sapper 中实现快捷键?
- java - 无法在 Gradle 中设置未知属性“applicationDefaultJvmArgs”
- wordpress - 如何将链接从结构重定向到另一个