Home > Software design >  BASH and jq to access JSON key-value pair
BASH and jq to access JSON key-value pair

Time:09-27

How can I access the key and value in BASH and/or jq?

I have a command shown below:

asg_name="bleh"
aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-names $asg_name | 
    jq -r '.AutoScalingGroups[].Instances[] | 
           {InstanceId: .InstanceId, HealthStatus: .HealthStatus, LifecycleState: .LifecycleState}'

which produces the following format:

{
  "InstanceId": "i-jibberish",
  "HealthStatus": "Healthy",
  "LifecycleState": "InService"
}
{
  "InstanceId": "i-jibberish",
  "HealthStatus": "Healthy",
  "LifecycleState": "InService"
}

How can I extract the value of each key in each JSON block (as the same row) so that I can use it in another process? Similar to the following effect:

for obj in $results
do
   if [ obj[ValueOfHealthStatus] = "Healthy" ] && [ obj[ValueLifeCycleState] = "InService" ]; then
      do_something(obj[ValueOfInstanceId])   
   fi
done

Is it possible at all?

Thanks

CodePudding user response:

Implemented as Bash logic:

#!/usr/bin/env bash

jq -s -j '.[]|(.InstanceId   "\u001f"   .HealthStatus   "\u001f"   .LifecycleState, "\u0000")' a.json |
while IFS=$'\37' read -r -d '' InstanceId HealthStatus LifecycleState; do
  if [ "$HealthStatus" == 'Healthy' ] && [ "$LifecycleState" == 'InService' ]; then
    echo do_something "$InstanceId"
  fi
done

Implemented as jq logic:

#!/usr/bin/env bash

jq -sj '.[]|if .HealthStatus=="Healthy" and .LifecycleState=="InService" then .InstanceId   "\u0000" else empty end' a.json |
while IFS= read -r -d '' InstanceID; do
  echo do_something "$InstanceID"
done

EDIT Forgot about jq select which is even more appropriate here than an if then else empty end:

#!/usr/bin/env bash

jq -sj '.[] | select(.HealthStatus == "Healthy" and .LifecycleState == "InService") | .InstanceId   "\u0000"' a.json |
while IFS= read -r -d '' InstanceID; do
  echo do_something "$InstanceID"
done
  • Related