使用基于日期的JQ过滤JSON数据

axr492tv  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(169)

JSON数据

{
  "DateTime": "2022-12-09T16:00:00.000Z",
  "Name": "name1"
}
{
  "DateTime": "2023-12-09T16:00:00.000Z",
  "Name": "name2"
}
{
  "DateTime": "2028-12-09T16:00:00.000Z",
  "Name": "name3"
}
{
  "DateTime": "2030-12-09T16:00:00.000Z",
  "Name": "name4"
}

要求结果:仅需过滤2022年至2030年之间的行
所需输出

{
  "DateTime": "2023-12-09T16:00:00.000Z",
  "Name": "name2"
}
{
  "DateTime": "2028-12-09T16:00:00.000Z",
  "Name": "name3"
}
apeeds0o

apeeds0o1#

一个简单的解决方案可能是从DateTime中获取第一个4字符,转换该tonumber并将其用作$year

然后select()所有$year > 2022 and $year < 2030

map((.DateTime[0:4] | tonumber) as $year | select($year > 2022 and $year < 2030))

更复杂的解决方案,其中我们 * 正确 * 解析日期:

map(.DateTime | (sub("(?<time>.*)\\.[\\d]{3}(?<tz>.*)"; "\(.time)\(.tz)") | fromdateiso8601 |  strftime("%Y") | tonumber) as $year | select($year > 2022 and $year < 2030))

这将使用subGithub Issue中删除日期的毫秒部分,以便fromdateiso8601能够理解它,并且我们可以使用strftime将其格式化为年份

产出

[
  {
    "DateTime": "2023-12-09T16:00:00.000Z",
    "Name": "name2"
  },
  {
    "DateTime": "2028-12-09T16:00:00.000Z",
    "Name": "name3"
  }
]

相关问题