0

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

user1555190
  • 2,803
  • 8
  • 47
  • 80
  • 1
    I would recommend jq: https://stedolan.github.io/jq/ – Wayne Vosberg Oct 06 '21 at 10:01
  • 1
    https://www.starkandwayne.com/blog/bash-for-loop-over-json-array-using-jq/ https://stackoverflow.com/questions/33950596/iterating-through-json-array-in-shell-script What have you tried? What research did you do? `data:[` is invalid json. – KamilCuk Oct 06 '21 at 10:09

2 Answers2

2

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
cisk
  • 589
  • 3
  • 13
1

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]}"
Léa Gris
  • 17,497
  • 4
  • 32
  • 41