Can someone please help me out?
I am working on a raspberry pi project and i wanted to control my pins from the cloud. I have this bash script that connects to a web service periodically to check this response. {"status":1,"pin":4}
I am using jq and i was able to get the values that i need using
source gpio
foo = $(curl '{webservice_url}')
echo ${foo} | jq '.status'
echo ${foo} | jq '.pin'
output : 1 and 4
problem is when i try to pass the value to a variable and use them it doesn't work
i tried:
foo = $(curl '{webservice_url}')
status = `${foo} | jq '.status'`
pin = `${foo} | jq '.pin'`
echo "$status"
echo "$pin"
I tried using echo ${status} and still the error says
status: command not found
pin: command not found
also i tried
source gpio
while true; do
foo = $(curl '{webservice_url}')
gpio mode "${foo} | jq '.pin'" out
gpio write "${foo} | jq '.status'" 1
sleep 1
done
but its not working.
Thank you in advance
Here is an illustration of how you can achieve what you want using bash and jq:
# foo=$(curl '{webservice_url}')
foo='{"status": "S", "pin": "P"}'
status=$(jq .status <<< ${foo})
pin=$(jq .pin <<< ${foo})
echo "$status"
echo "$pin"
Since this involves one invocation of jq per variable, it might be worthwhile using an alternative approach. If your bash has readarray
(aka mapfile
), then consider:
readarray -t lines <<< $(jq -cr .status,.pin <<< ${foo})
status=${lines[0]}
pin=${lines[1]}
Otherwise:
i=0
while read -r line
do
i=$((i+1))
a[$i]="$line"
done < <(jq -cr .status,.pin <<< ${foo})
Here's a slightly different approach that relies on the fact that literal tabs cannot appear in JSON strings:
IFS=$'\t' read status pin < <(jq -r '[.status,.pin]|@tsv' <<< ${foo})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.