1

I have a JSON output from which I need to extract an ID and Iterate through them and send multiple request to API execute REST API with curl. For example:

This is how the JSON output looks like:

{
    "glossary": [
        {
            "Title": "example glossary1",
            "id": 1,
            "description": "Hello Glossary1"
        },
        {
            "Title": "example glossary2",
            "id": 2,
            "description": "Hello Glossary2"
        },
        {
            "Title": "example glossary3",
            "id": 3,
            "description": "Hello Glossary3"
        },
        {
            "Title": "example glossary4",
            "id": 4,
            "description": "Hello Glossary4"
        }
    ]
}

The shell script should loop through this JSON file, extract the ID and loop through and execute REST API calls with CURL.

Here is example:

for (( i = 0 ; i < ${#id[@]} ; i++ ))
do 
     POST REST API 
done

4 Answers 4

2

If you have you output in a file called tmp.json use jq to get the list of ids, one per line and then with a simple for loop make a post to your api

for i in `cat tmp.json  | jq .glossary[].id`; do 
   curl -X POST http://host/api/$i"
done
0

Here's an example, just using awk:

#!/bin/bash

for id in $(awk '/"id":/ {sub(/,/, ""); print $2}' inputfile.json); do
    curl -X POST ...
done
0

Without awk up to 3 digit ids. Just push your JSON result through STDIN and read with a while loop:

digits=0; 
while read line
do 
  foo=`echo $line|grep id|cut -c 7-$((7+digits))`
  if [[ ! $foo -eq '' ]]
    then 
      echo "curl http://webaddress/api?id=$foo"
      if [[ '$foo' == '9' ]] || [[ '$foo' == '99' ]]
      then 
        digits=$((digits+1)) 
      fi 
  fi 
done<your-json-output.json
0

Curl allows you to make several requests to the same endpoint at once by using curly braces ({...}) in the URL.

For example, if your endpoint is

http://example.com/api/endpoint

then you may call this with three values of some parameter id like so:

curl 'http://example.com/api/endpoint?id={123,345,456}'

To get the IDs out of your JSON document as a comma-delimited set of integers in curly braces, use jq like so:

jq -r '.glossary | map(.id) | "{\(join(","))}"' file

For the given document in the question, this would return the string {1,2,3,4}.

You may then use this in your single call to curl:

ids=$( jq -r '.glossary | map(.id) | "{\(join(","))}"' file )

curl -s "http://example.com/api/endpoint?id=$ids"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .