I have a json file which i have obtained using curl command and it looks as below.
{
"Storages": [
{
"Creation": "2020-04-21T14:01:54",
"Modified": "2020-04-21T14:01:54",
"Volume": "/dev/null",
"id": 10000,
"version": "20190925-230722"
},
{
"Creation": "2020-04-22T14:01:54",
"Modified": "2020-04-22T14:01:54",
"Volume": "/opt/home",
"id": 10001,
"version": "22a-20190925-230722"
},
{
"Creation": "2020-04-23T14:01:54",
"Modified": "2020-04-23T14:01:54",
"Volume": "/home/abcd",
"id": 10003,
"version": "21c-20190925-230722"
}
]
}
Now I need to form another json by looping through above json array and get the keys (id and voulme) from each array if version starts with 21a.
CodePudding user response:
You can use startswith
builtin function such as
jq -r '.Storages[] | select(.version | startswith("21a")) | {id: .id, Volume: .Volume}'
CodePudding user response:
For educational purposes, here's a jq
command that does both the things you want, but in 2 separate steps:
jq -r 'del(.Storages[] | select(.version | startswith("21a") | not))
.Storages[] | {id, version}'
The first part (del(.Storages[] | select(.version | startswith("21a") | not))
) filters out the array elements that don't have a version starting with 21a
. The second part (.Storages[] | {id, version}
) drills and extracts the specific information you need.