Shell Script: Iterate over json array

I have a jsons array that I need to iterate over. I make a curl and get this result, and I need to process it. The array is as follows:

 [
{"id": "f0345a01", "name": "scala1"},
 {"id": "6f907cf", "name": "scala2"}, 
{"id": "d887f61", "name": "scala3"}, 
{"id": "5d07fca", "name": "scala5"}, 
{"id": "94ddaa", "name": "scala12"}
]

I need to get the id from this array. I could not find a way to do this. I tried the following question about stackoverflow:

for i in "${arr[@]}" 
do
    echo "$i"

done
+4
source share
5 answers

Use jqto get identifiers:

curl http://... | jq -r '.[].id'

You can pass this to the bash loop whileif you want to do further processing:

curl http://... | jq -r '.[].id' | while read id ; do
    do_something "${id}"
done
+7
source

Use PCRE Grep compatible

jq (, , ), grep . , , , , ..

id, grep PCRE, pcregrep. , tr. :

$ pcregrep -o '"id": \K"[[:xdigit:]]{7,8}"' <<< "$result" | tr -d \"
f0345a01
6f907cf
d887f61
5d07fca

, grep, - , .

+2

,

[
{"id": "f0345a01", "name": "scala1"},
{"id": "6f907cf", "name": "scala2"}, 
{"id": "d887f61", "name": "scala3"}, 
{"id": "5d07fca", "name": "scala5"}, 
{"id": "94ddaa", "name": "scala12"}
]

- :

curl -s "your_link" | awk '{print $2}' | tr -d '",'

:

cat sample | awk '{print $2}' | tr -d '","'

f0345a01
6f907cf
d887f61
5d07fca
94ddaa
+1

" ":

ids=$(echo "${arr}" | tr -s '\n' ' ' | tr -s ',' '\n' \
    | grep '"id"\s*:' | cut -d '"' -f 4)
for i in ${ids}
do
    echo "===> $i"
done

, , , , grep/cut , .

  • tr -s '\n' '' , , "id"
  • tr -s ',' '\n' ,
  • grep ' "id" \s *:' grep "id"
  • finally cut -d '"' -f 4
+1

awk ( )

 YourCurlStream | awk 'NF>1{gsub( /[":,{}]/, "");$0=$0;print $2 }'
+1

Source: https://habr.com/ru/post/1676657/


All Articles