Home > other >  Bash looping over returned Json using curl
Bash looping over returned Json using curl

Time:10-06

So i make a curl command to a url which returns an array of objects

response= $(curl --locaiton --request GET "http://.....")

I need to iterate over the returned json and extract a single value..

The json is as follows:

{
   data:[
    {"name": "ABC", "value": 1},
    {"name": "EFC", "value": 4},
    {"name": "CEC", "value": 3}
   ]
}

Is there anyway in BASh i can extract the second object value.. by perhaps iterating and doing an IF

CodePudding user response:

Use jq

A simple example to extract the 2nd entry of the array would be:

RESPONSE='{"data":[{"name":"ABC","value": 1},{"name":"EFC","value":4},{"name":"CEC","value":3}]}';
EXTRACTED=$(echo -n "$RESPONSE" | jq '.data[1]');
echo $EXTRACTED

CodePudding user response:

jq is the most commonly used command/tool to parse JSON data from a shell script. Here is an example with your data:

#!/usr/bin/env sh

# JSON response
response='
{
  "data": [
    {"name": "ABC", "value": 1},
    {"name": "EFC", "value": 4},
    {"name": "CEC", "value": 3}]
}'

# Name of entry
name='EFC'

# Get value of entry
value=$( jq --null-input --raw-output --arg aName "$name" \
  "$response"' | .data[] | select(.name == $aName) | .value')

# Print it out
printf 'value for %s is: %s\n' "$name" "$value"

Alternatively jq can be used to transform the whole JSON name value objects array, into a Bash associative array declaration:

#!/usr/bin/env bash

# JSON response
response='
{
  "data": [
    {"name": "ABC", "value": 1},
    {"name": "EFC", "value": 4},
    {"name": "CEC", "value": 3}]
}'

# Name of entry
name='EFC'

# Covert all JSON array name value entries into a Bash associative array
# shellcheck disable=SC2155 # safe generated declaration 
declare -A entries="($( jq --null-input --raw-output \
  "$response"' | .data[] | ( "["   ( .name | @sh )   "]="   (.value | @sh) )'))"

# Print it out
printf 'value for %s is: %s\n' "$name" "${entries[$name]}"
  •  Tags:  
  • bash
  • Related