简体   繁体   中英

BASH and jq to access JSON key-value pair

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM