Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a date range from a JSON string by using jq?

Tags:

json

shell

macos

jq

I have a JSON string like this (MacOS):

[{
    "id": 3624,
    "created_at": "2016-10-21T20:51:16.000+08:00",
  },
  {
     "id": 3625,
    "created_at": "2016-10-22T08:09:16.000+08:00",
  },
 {
     "id": 3626,
    "created_at": "2016-10-23T09:19:55.000+08:00",
  }]

I wanna select "created_at" from "2016-10-21" to "2016-10-22"; I wanna get result like this:

[{
    "id": 3624,
    "created_at": "2016-10-21T20:51:16.000+08:00",
  },
  {
     "id": 3625,
    "created_at": "2016-10-22T08:09:16.000+08:00",
  }]

Can someone point me in the right direction?

The problem is solved. Now,i use this code to select date right to the minute,i hope it's useful for others:

jq --arg s '2016-10-26T18:16' --arg e '2016-10-27T20:24' '[($s, $e) | strptime("%Y-%m-%dT%H:%M") | mktime] as $r
  | map(select(
        (.updated_at[:19] | strptime("%Y-%m-%dT%H:%M:%S") | mktime) as $d
          | $d >= $r[0] and $d <= $r[1]))' <<< "$requestJson"
like image 810
GrumpyMelon Avatar asked Dec 19 '22 12:12

GrumpyMelon


1 Answers

For a more robust solution, it would be better to parse the dates to get its components and compare those components. The closest you can get is to use strptime/1 to parse the date which returns an array of its components. Then compare the components to check if it's in range.

The array that strptime returns are the components:

year (%Y)
month (%m)
date (%d)
hours (%H)
minutes (%M)
seconds (%S)
day of week (%w)
day of year (%j)

Since you're only comparing the dates, the comparisons should only look at the first 3 components.

$ jq --arg s '2016-10-21' --arg e '2016-10-22' '
[($s, $e) | strptime("%Y-%m-%d")[0:3]] as $r
  | map(select(
        (.created_at[:19] | strptime("%Y-%m-%dT%H:%M:%S")[0:3]) as $d
          | $d >= $r[0] and $d <= $r[1]
    ))
' input.json

Since you're running on a Mac, I'd expect these methods would be available to you in your build. You may have to make adjustments to the format of the dates for it to work as expected. As you can see in the comments, we had to massage it a bit to make it work.

like image 169
Jeff Mercado Avatar answered Jan 11 '23 15:01

Jeff Mercado