Reputation: 1492
I have a JSON variable from curl like the below (@stackoverflow=pretty printed) and I want to get two pieces of information. The date which is the first calendar date and the last calendar date (ISO 8601), but I have no idea how to do this in bash. On top I have to calculate the duration between these two dates (could be just some milliseconds or much more).
Anyone any idea how I can solve my problem?
{
"results": [{
"...": "...",
"date": "2012-09-15T14:04:00.741+0200",
"...": "..."
},
{
"...": "...",
"date": "2015-09-15T14:04:00.741+0200",
"...": "..."
},
{
"...": "...",
"date": "2015-09-11T14:04:00.741+0200",
"...": "..."
},
{
"...": "...",
"date": "2015-09-15T14:04:00.741+0200",
"...": "..."
},
{
"...": "...",
"date": "2015-09-15T14:04:30.741+0200",
"...": "..."
},
{
"...": "...",
"date": "2019-09-15T14:04:00.741+0200",
"...": "..."
},
{
"...": "...",
"date": "1015-09-15T14:04:00.741+0200",
"...": "..."
}]
}
For your information: Its a test script I have to use, because there is some more magic in it I don't want to rewrite in other script languages.
Upvotes: 0
Views: 400
Reputation: 1492
Here is what works for me:
echo $JSON | tr '"' '\n' | sed -n '/date/{n;n;p}'
dates=$(echo $JSON | tr '"' '\n' | sed -n '/date/{n;n;p}')
for date in ${dates[@]}
do
echo $date
done
Upvotes: 0
Reputation: 532053
Use jq
to parse the JSON and extract all the dates, then sort them and output the first and last dates.
curl ... | jq '.results[] | .date' | sort | awk 'NR==1; END {print}'
Upvotes: 2
Reputation: 212514
It's not clear exactly what the setting is, but if you have text in a variable names JSON, you can extract the lines containing the desired dates with:
echo "$JSON" | awk '/date/ && !a++; /date/ {l=$0} END {print l}'
(Depending on the deleted content; you might get some false hits and need a more tightly constrained regex). But parsing json with shell tools is really a bad idea.
Upvotes: 1