Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script: Iterating over array of json

Tags:

bash

shell

I have an array of jsons which I need to iterate over. I do a curl call and get this result and need to process it for something. The array looks like this:

 [
{"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's from this array. I could not find any way to do so. I tried this following another stackoverflow question:

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

done
like image 647
Dreams Avatar asked Nov 21 '25 09:11

Dreams


2 Answers

Use jq to obtain the ids:

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

You can pipe that into a bash while loop if you want to perform further processing:

curl http://... | jq -r '.[].id' | while read id ; do
    do_something "${id}"
done
like image 78
hek2mgl Avatar answered Nov 23 '25 23:11

hek2mgl


If you're curl does get you this formatted list

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

Then just doing something like:

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

OUTPUT:

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

f0345a01
6f907cf
d887f61
5d07fca
94ddaa
like image 25
OrangesV Avatar answered Nov 23 '25 21:11

OrangesV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!