0

Using bash, i'm calling an API using curl and storing the result in a variable. That result is an array. An example of the structure of the response is below.

[
{"id":1,"name":"this is the name","description":"this is the description"},
{"id":2,"name":"this is the name","description":"this is the description"},
{"id":3,"name":"this is the name","description":"this is the description"}
]

I want to be able to iterate through and get the value of "id". Then use that id as part of another curl call. How could I achieve this using bash?

Carm V
  • 29
  • 1
  • 3
    You might want to have a browse through this Q&A: [Parsing Json with Unix tools](https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools) – lurker Dec 17 '20 at 03:00

2 Answers2

0

You can use jq to extract the id values and readarray to store them in a bash array for later processing:

#!/usr/bin/env bash

json='
[
{"id":1,"name":"this is the name","description":"this is the description"},
{"id":2,"name":"this is the name","description":"this is the description"},
{"id":3,"name":"this is the name","description":"this is the description"}
]
'

readarray -t ids < <(jq '.[] | .id' <<<"$json")

for id in "${ids[@]}"; do
    printf "Id %d\n" "$id"
done
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • If you just need one at a time, storing them in a Bash array is just a waste of memory. Try `jq '.[] | .id' <<<"$json" | while read -r id; do ...` – tripleee Dec 17 '20 at 11:47
0

Try sed

curl $YOUR_URL | sed -n 's/.*"id":\(.*\),"name".*/\1/p'
1
2
3
Ivan
  • 6,188
  • 1
  • 16
  • 23