Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question

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
share|improve this answer

Here's an example, just using awk:

#!/bin/bash

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

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.