I'm having trouble doing a seemingly trivial task. Say I've got an API response with a following json output:
[
{
"id": 47,
"iid": 12,
"project_id": 1,
"status": "pending",
"soure": "push",
"ref": "new-pipeline",
"sha": "a91957a858320c0e17f3a0eca7cfacbff50ea29a",
"web_url": "https://example.com/foo/bar/pipelines/47",
"created_at": "2016-08-11T11:28:34.085Z",
"updated_at": "2016-08-11T11:32:35.169Z"
},
{
"id": 48,
"iid": 13,
"project_id": 1,
"status": "pending",
"soure": "web",
"ref": "new-pipeline",
"sha": "eb94b618fb5865b26e80fdd8ae531b7a63ad851a",
"web_url": "https://example.com/foo/bar/pipelines/48",
"created_at": "2016-08-12T10:06:04.561Z",
"updated_at": "2016-08-12T10:09:56.223Z"
}
]
I want to keep only those objects whose 'created_at' date matches current date. What would be the best way/tools for this job?
CodePudding user response:
This is a job for jq
# `printf` can do strftime stuff
today=$(printf '%(%Y-%m-%d)T' -1) # magic value "-1" is "now"
echo "$response" | jq --arg date "$today" '[.[] | select(.created_at | startswith($date))]'
Or, all in jq
echo "$response" | jq '
(now | strftime("%F")) as $today |
[.[] | select(.created_at | startswith($today))]
'
CodePudding user response:
With the JSON parser xidel you could either do a string comparison, checking whether created_at
starts with the current date as a string:
$ xidel -s input.json -e '$json()[starts-with(created_at,"'$(date ' %Y-%m-%d')'")]'
$ xidel -s input.json -e '$json()[starts-with(created_at,substring(current-date(),1,10))]'
$ xidel -s input.json -e '$json()[starts-with(created_at,format-date(current-date(),"[Y]-[M01]-[D01]"))]'
Or you could do a logical date comparison:
$ xidel -s input.json -e '$json()[date(substring-before(created_at,"T")) eq current-date()]'