My current script is returning "userAccessId" value for all the blocks under "useraccesses". Below i have written the script and backend json response. I have filtered and getting "userAccessId" value for all the blocks under "useraccesses".
But my actual requirement is, i want to get "userAccessId" value whose "numberOfAccessSchedules" value are greater than zero. Can someone please modify my script.
MyScript.sh
#!/bin/sh
#
export TOKEN=$(curl -k -s -d "client_id=guard-public" -d "grant_type=password" -d "username=test" -d "password=test@123" "https://10.00.00.00/auth/realms/guard/protocol/openid-connect/token" | python -c "import sys, json; print json.load(sys.stdin)['access_token']")
#GET UserAccess ID
#echo "GET useraccess ID for all users"
curl -k --location --request GET "https://10.00.00.00:111/guardian-restservice/v1/useraccesses?page=$i&page_size=10000" -k -H "Authorization: bearer $TOKEN" | jq | grep "userAccessId" | awk -F : {'print $2'} | sed 's/,//' >> alluseraccessId.txt
Backend JSON Response without filter
{
"page": {
"currentPage": 1,
"totalPages": 7,
"pageSize": 10000
},
"useraccesses": [
{
"userAccessId": 918568786,
"numberOfAccessSchedules": 2,
"customAttributes": {},
"networkElementUserId": ""
},
{
"userAccessId": 918569013,
"numberOfAccessSchedules": 1,
"customAttributes": {},
"networkElementUserId": ""
},
{
"userAccessId": 918569301,
"numberOfAccessSchedules": 0,
"customAttributes": {},
"networkElementUserId": ""
},
...........
...........
...........
]
}
Current O/P (alluseraccessId.txt)
918568786 918569013 918569301
Expected O/P (alluseraccessId.txt)
918568786 918569013
CodePudding user response:
You can easily extract the values you need with jq
, the de facto standard utility for working with JSON in shell scripts. Trying to apply regular expression based tools to structured data formats like JSON or XML is almost always a bad idea.
curl ... | jq '.useraccesses[] | select(.numberOfAccessSchedules>0) | .userAccessId' >> alluseraccessId.txt
Adds
918568786
918569013
to the file.
Means 'for each element of the array in the useraccesses
element of the top level object, if its numberOfAccessSchedules
element is greater than 0, print the value of its userAccessId
element.'